![]() |
#2
lzb66892013-09-27 09:56
为了找到原因,我把代码转化为Delphi程序,结果速度超快,试了几次均为0秒钟解决问题,这就奇怪了,平时都是vc++略快一些过Delphi,现在却倒了过来。
以下是delphi代码: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,math; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var h,i,j,k,l,m,n,p:integer; a,b,c:int64; x,z,t1,t2,t3: double ; s:string; begin s:=trim(self.Edit1.Text ); if s<>'' then n:=strtoint(s) else n:=1; if n>32 then n:=32; t1:=now; self.Memo1.Clear ; for i:=2 to n do begin p:=i;m:=0; x:=p;z:=sqrt(x);h:=trunc(z); if(h<(p-1)) then h:=h+1; for j:=2 to h do begin if((p mod j)=0) then begin m:=1;break; end; end; if(m=0) then begin a:=1; for k:=1 to p do begin a:=a*2; end; a:=a-1; x:=a;z:=sqrt(x);h:=trunc(z)+1; l:=0; for j:=2 to h do begin b:=j; if((a mod b)=0) then begin l:=l+1; break; end; end; if(l=0) then begin if (a<3037000499) then c:=trunc(a*(a+1)/2) else c:=a; s:=' 质数: '+ inttostr(i)+' '; if(a<3037000499) then s:=s+'完数= '+inttostr(c) else s:=s+'素数= '+inttostr(c); self.Memo1.Lines.Append(s); end; end; end; t2:=now; t3:=(t2-t1)*86400; s:=' t= '+floattostr(t3); self.Memo1.Lines.Append(s); end; end. |
以下是一个求完全数的程序,我用vc++2010编译后运行,发现速度不是一般的慢,共耗时132.969秒钟,尝试了多种优化措施,变化不大,各位大大帮忙看看是什么原因。
以下是源代码:
// 完数.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <time.h>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
clock_t start, finish;
int h,i,j,k,l,m,n,p;
long long a,b,c;
double x,z;
cout<<"n=";
cin>>n;
cout<<endl;
if(n<1) n=1;
if(n>32)n=32;
start = clock();
for(i=2;i<=n;i++)
{
p=i;m=0;
x=p;z=sqrt(x);h=int(z);
if(h<(p-1)) h++;
for(j=2;j<=h;h++)
{
if((p % j)==0)
{
m=1;break;
}
}
if(m==0)
{
a=1;
for(k=1;k<=p;k++)
{
a*=2;
}
a=a-1;
x=(double)a;z=sqrt(x);h=int(z)+1;
l=0;
for(j=2;j<=h;j++)
{
b=j;
if((a % b)==0)
{
l++;
break;
}
}
if(l==0)
{
if(a<3037000499) c=a*(a+1)/2; else c=a;
cout<<" 质数: "<<i<<" ";
//cout<<endl;
if(a<3037000499) cout<<"完数= "<<c;else cout<<"素数= "<<c;
cout<<endl;
}
}
}
finish = clock();
z= (double)(finish - start) / CLOCKS_PER_SEC;
cout<<"t= "<<z;
system("pause");
return 0;
}