质因数分解

codevs 1792 分解质因数

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 青铜 Bronze
题目描述 Description

编写一个把整数N分解为质因数乘积的程序。

输入描述 Input Description

输入一个整数 N

输出描述 Output Description

输出 分解质因数 。拆成几个质数相乘的形式,质数必须从小到大相乘

样例输入 Sample Input

756

样例输出 Sample Output

756=2*2*3*3*3*7

数据范围及提示 Data Size & Hint

范围在longint内。不是高精度。

 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 long long n,ni;
 5 #define N 100000
 6 #include<cmath>
 7 int prime[N],p=0;
 8 int ans[N],ai=0;
 9 int main()
10 {
11     cin>>n;
12     ni=n;
13     prime[++p]=2;
14     for(int i=3;i<=n;++i)
15     {
16         bool flag=true;/*先生成一个1--n的质数数列*/
17         for(int j=2;j<=sqrt(i);++j)
18         {
19             if(i%j==0)
20             {
21                 flag=false;
22                 break;
23             }
24         }
25         if(!flag) continue;
26         prime[++p]=i;
27     }
28     while(n!=1)/*使用短除法来分解质因数*/
29     {
30         for(int i=1;i<=p;++i)/*枚举所有质数*/
31           if(n%prime[i]==0)/*每次找到质因数后就break,保证每次找到最小的质因数*/
32           {
33               n/=prime[i];/*除去它*/
34               ans[++ai]=prime[i];/*储存答案*/
35               break;
36           }
37     }
38     cout<<ni<<"=";
39     for(int i=1;i<ai;++i)
40       printf("%d*",ans[i]);
41     printf("%d",ans[ai]);
42     return 0;
43 }
原文地址:https://www.cnblogs.com/c1299401227/p/5506315.html