Time limit
3000 ms
OS
Linux

Write a program, that computes the number of different prime factors in a positive integer.
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有多少个质因数。

分析:因为n<=1000000,time limit 3000ms,所以直接枚举所有当前小于n的素数即可。

欧拉筛预处理素数。

在枚举素数的过程中,如果该素数是n的质因数,那么就把n不断地除去该素数直到小于该素数,如果当前枚举的素数大于n,直接break即可。

AC code:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. bool u[1000005];
  4. int su[1000005];
  5. int num;
  6. void olas()
  7. {
  8. num=1;
  9. memset(u,true,sizeof(u));
  10. for(int i=2;i<=1000000;i++)
  11. {
  12. if(u[i]) su[num++]=i;
  13. for(int j=1;j<num;j++)
  14. {
  15. if(i*su[j]>1000000) break;
  16. u[i*su[j]]=false;
  17. if(i%su[j]==0) break;
  18. }
  19. }
  20. }
  21. int main()
  22. {
  23. //freopen("input.txt","r",stdin);
  24. olas();
  25. int n;
  26. while(~scanf("%d",&n)&&n)
  27. {
  28. int tmp=n;
  29. int ans=0;
  30. for(int i=1;i<num;i++)
  31. {
  32. if(n<su[i]) break;
  33. if(n%su[i]==0)
  34. {
  35. ans++;
  36. while(n%su[i]==0)
  37. {
  38. n/=su[i];
  39. }
  40. }
  41. }
  42. printf("%d : %d\n",tmp,ans);
  43. }
  44. return 0;
  45. }

View Code

 

版权声明:本文为cautx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/cautx/p/11434817.html