看看能不能整除,
能整除就一直除到不能,
做完後再看看輸入的值是否已經被除到只剩下1,
如果不是,一定只是一個大於輸入的值的根號的質數,將之輸出即可。
[C++](6ms, 700KB)
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 ) | |
{ | |
bool print = 0; | |
int num; | |
int limit = static_cast<int>(sqrt(x)); | |
for( int i = 2; i <= limit; i++ ) | |
{ | |
num = 0; | |
while( x % i == 0 ) | |
{ | |
num++; | |
x /= i; | |
} | |
if( num ) | |
if( print ) | |
{ | |
cout << " * " << i; | |
if( num != 1 ) | |
cout << '^' << num; | |
} | |
else | |
{ | |
print = 1; | |
cout << i; | |
if( num != 1 ) | |
cout << '^' << num; | |
} | |
} | |
if( x != 1 ) | |
if( print ) | |
cout << " * " << x; | |
else | |
cout << x; | |
cout << endl; | |
} | |
return 0; | |
} |
0 意見:
張貼留言