TJU Count the factors

35 篇文章 0 订阅
13 篇文章 0 订阅

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;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值