所以用個for從頭跑到尾就可以了。
為了省時,可以僅跑到輸入值的根號處即可。
[C++](20ms, 670KB)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<cmath> | |
using namespace std; | |
int main() | |
{ | |
int x; | |
while( cin >> x ) | |
{ | |
if( x == 2 ) | |
printf( "質數\n" ); | |
else if( x % 2 == 0 ) | |
printf( "非質數\n" ); | |
else | |
{ | |
int primeis = 1; | |
for( int i = 3 ; i <= sqrt(x); i++ ) | |
{ | |
if( x % i == 0 ) | |
{ | |
printf( "非質數\n"); | |
primeis = 0; | |
} | |
} | |
if( primeis ) | |
printf( "質數\n" ); | |
} | |
} | |
return 0; | |
} |
3 意見:
應在判斷到非質數立刻break會快得多
sqrt(x)用前先算好放入變數避免每跑一個I都計算
感謝提供意見,
移植到新Blog會改寫一下程式^_^/
張貼留言