Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7759 Accepted Submission(s): 4724
Problem Description
Eddy's interest is very extensive, recently he is interested in prime number. Eddy discover the all number owned can be divided into the multiply of prime number, but he can't write program, so Eddy has to ask intelligent you to help him, he asks you to write a program which can do the number to divided into the multiply of prime number factor .
Input
The input will contain a number 1 < x<= 65535 per line representing the number of elements of the set.
Output
You have to print a line in the output for each entry with the answer to the previous question.
Sample Input |
11 9412 |
Sample Output |
11 2*2*13*181 |
題意:每個數都能拆成一個或多個素數的乘積,輸入一個數,求輸出這些素數。
解題思路:就是直接用for循環判斷是否爲素數並且是否能被整除,然後存在一個數組裏面依次輸出。之前直接這樣寫超時了。將0~65536之間的素數存在一個數組裏面,然後一個個判斷是否能整除,就過了。
code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
using namespace std;
int is_prime(int n)
{
for(int i=2;i<=n/2;i++)
if(n%i==0)
return 0;
return 1;
}
int a[65536];
int pri[65536];
int main()
{
int n;
int cnt=0;
for(int i=2;i<65540;i++){
if(is_prime(i))
pri[cnt++]=i;
}
while(scanf("%d",&n)!=EOF)
{
int k=0;
if(is_prime(n))
printf("%d\n",n);
else{
for(int i=0;i<=n;i++){
while(n%pri[i]==0){
a[k++]=pri[i];
n/=pri[i];
}
if(n==1)
break;
}
for(int i=0;i<k-1;i++){
printf("%d*",a[i]);
}
printf("%d\n",a[k-1]);
}
}
return 0;
}