• 分解质因子


    题目描述
    把一个数分解成如干个质数相乘.

    程序输入说明

    有多组测试数据,每组包含一个整数N,N小于100000000
    tatsuya的补充:N>=2,以EOF结束输入

    程序输出说明

    输出分解出的因式
    tatsuya的补充:每组输入对应一行输出,因子从小到大依次排列,每两个因子以一个空格分隔

    程序输入样例

    6 
    9

    程序输出样例

    2 3
    3 3
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    
    typedef unsigned long DWORD;
     
    //函数decomp_integer对n分解素因数,分解后的素数存入facArr数组,并返回因子的个数
    int decomp_integer( DWORD n, DWORD facArr[])
    {
        DWORD fac;      //n的可能的一个因子
        int count;
     
        if (n<4)        //4以内的数,不需要分解
        {   
            facArr[0]=n; 
            return 1;  
        }
     
        count=0;
        //下面的while循环为2试出n,直到2不是n的因子为止
        while ( (n & 1)==0) // 这里判断偶数用 (n &1)==0,这比(n % 2)==0更快
        {
            facArr[count++]=2;  
            n/=2;
        }
     
        fac=3;  //用3到sqrt(n)之间的奇数试除
        while (fac*fac<=n) // fac*fac <= n
        {
            while (n % fac==0)
            {
                facArr[count++]=fac;
                n /= fac;
            }
            fac+=2;
        }
        if (n==1)
            return count;
     
        facArr[count++]=n;
        return count;
    }
     
    int main()
    {
        DWORD n,facArray[10000];
        int i,count;
        while( scanf("%u",&n) != EOF ){
            count=decomp_integer(n,facArray);
            for( i = 0; i < count; i++ )
                cout<<facArray[i]<<" ";
            cout<<endl;
        }
        return 0;
    }

  • 相关阅读:
    【OC 知识】静态变量
    【OC知识点】alloc 和init
    【oc 知识点】copy和mutableCopy
    【iOS入门】pod 安装
    【iOS入门】NSarray
    【iOS入门】instancetype和id的区别
    【iOS入门】不全屏
    【ios入门】xcode 新建项目变化
    Spark(一)-- Standalone HA的部署
    数据挖掘算法之协同过滤算法
  • 原文地址:https://www.cnblogs.com/geziyu/p/10152921.html
Copyright © 2020-2023  润新知