分解质因数

分解质因数:

1.保留重复

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);}
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1,class T2>inline void gmax(T1 &a,T2 b){if(b>a)a=b;}
template <class T1,class T2>inline void gmin(T1 &a,T2 b){if(b<a)a=b;}
const int N=1e5,M=1e6,Z=1e9+7,ms63=0x3f3f3f3f;
int a[N],n;
int main()
{
    while(cin >> n)
    {
        int num = 0;
        for(int i=2; i*i<=n; i++)
        {
            //if(n % i == 0) //是n的因子
            //{
                //a[num++] = i;
                while(n % i ==0){ //不断分解直到为质数
                    a[num++] = i;
                    n /= i;
                }
            //}
        }
        if(n>1) a[num++] = n; //如果n最后剩下的是一个大于1的数,那么这是最大的质因子
        for(int i=0; i<num; i++){
            printf("%d ",a[i]);
        }
        printf("
");
    }
}
/*
120
2 2 2 3 5
*/
View Code

2.不保留重复

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);}
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1,class T2>inline void gmax(T1 &a,T2 b){if(b>a)a=b;}
template <class T1,class T2>inline void gmin(T1 &a,T2 b){if(b<a)a=b;}
const int N=1e5,M=1e6,Z=1e9+7,ms63=0x3f3f3f3f;
int a[N],n;
int main()
{
    while(cin >> n)
    {
        int num = 0;
        for(int i=2; i*i<=n; i++)
        {
            if(n % i == 0) //是n的因子
            {
                a[num++] = i;
                while(n % i ==0){ //不断分解直到为质数
                    n /= i;
                }
            }
        }
        if(n>1) a[num++] = n; //如果n最后剩下的是一个大于1的数,那么这是最大的质因子
        for(int i=0; i<num; i++){
            printf("%d ",a[i]);
        }
        printf("
");
    }
}
/*
120
2 3 5
*/
View Code

以上的两种方法都是用朴素的整除性来判断是否是素数。

也可以用筛法先筛出素数,存在数组中,那么就是n % prime[i] == 0

原文地址:https://www.cnblogs.com/Roni-i/p/8783784.html