TJU Count the factors

The Problem

Write a program, that computes the number of different prime factors in a positive integer.

The Input

The input tests will consist of a series of positive integers. Each number is on a line on its own. The maximum value is 1000000. The end of the input is reached when the number 0 is met. The number 0 shall not be considered as part of the test set.

Output

The program shall output each result on a line by its own, following the format given in the sample output.

Sample Input

289384
930887
692778
636916
747794
238336
885387
760493
516650
641422
0

Sample Output

289384 : 3
930887 : 2
692778 : 5
636916 : 4
747794 : 3
238336 : 3
885387 : 2
760493 : 2
516650 : 3
641422 : 3
 
  
 
  
题意概述:给出一个数n(n<=106),问这个数有多少个质因数。如:9=3*3,但只有一个质因子。

解题思路:106是一个比较大的数。首先想到的方法是把素数存起来使用,这样可以节省一些时间。但是如果要把106内的素数计算出来还是有很大工作量的。其实,对于一个数n,在sqrt(n)到n之间最多只有一个质因数。那么我们也就只需要计算1000之内的素数了。除掉n中的所有小于sqrt(n)的质因数,有几个除几个,如果剩下1,那么就不存在sqrt(n)到n之间的质因数,反之则存在。那么我们计数的工作量就大大减少了。
 
源代码:
 
#include<iostream> #include<cmath> #include<set> using namespace std; int main() {     set<int>prime;     prime.insert(2);     prime.insert(3);     for(int i=5;i<1000;i+=2) //计算素数     {         bool flag=true;         double i1=(double)i;         for(int j=2;j<=(int)sqrt(i1);++j)               if(i%j==0){flag=false;break;}         if(flag)prime.insert(i);     }          int N;     set<int>::iterator pos;     while(cin>>N&&N)     {         int sum=0;         int temp=N,num=0;         for(pos=prime.begin();pos!=prime.end()&&N>=*pos;++pos)         {               num=*pos;               if(N%num==0)               {                     ++sum;                     while(N%num==0)N/=num;               }         }         if(N!=1)++sum;         cout<<temp<<" : "<<sum<<endl;     }     return 0; }  


你可能感兴趣的:(TJU Count the factors)