#include<iostream>
using namespace std;
int main()
{
int box,v;
while(cin >> v)
{
box = v/2;
if( v < 6 )
{
box = box * 2;
}
for( int a = 2; a <= box; a++ )
{
if( v % a == 0 )
{
cout << "非質數" << endl;
break;
}
else if( a == box )
{
cout << "質數" << endl;
break;
}
}
}
return 0;
}
box = v/2;
除以2還是要處理太多了
如果要處理最大值2147483647 for要跑十億次= =
開根號吧 ...最大只要處理四萬次~明顯快很多~
(找質數找到開根號就夠了)
#include
using namespace std;
int main()
{
int box,v;
while(cin >> v)
{
box = v/2;
if( v < 6 )
{
box = box * 2;
}
for( int a = 2; a <= box; a++ )
{
if( v % a == 0 )
{
cout << "非質數" << endl;
break;
}
else if( a == box )
{
cout << "質數" << endl;
break;
}
}
}
return 0;
}
我已經開根號了,可是還是慢了一秒耶~!
幫我看一下哪裡錯誤吧~!卸卸~!
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int v,c = 0;
while( cin >> v )
{
cout << "sqrt(v) = " << sqrt(v) << endl;
for( int a = 2; a <= sqrt(v); a++ )
{
cout << "a = " << a << endl;
if( v % a == 0 )
{
cout << "非質數" << endl;
break;
}
else if( a == int(sqrt(v)) )
{
cout << "質數" << endl;
}
}
}
return 0;
}