【hdoj 1164】Eddy's research I

Eddy's research I
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;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章