项目场景:
Time Limit: | 1000 ms |
Memory Limit: | 128 MB |
Case score: | 10 |
Level: | 4 |
Type: | Traditional Problem |
Validator: | Generic Comparsion |
问题描述
1318 -- 因式分解
Description
将大于 11 的自然数 NN 进行因式分解,满足 N=a[1]*a[2]*a[3]*…*a[m]N=a[1]∗a[2]∗a[3]∗…∗a[m] 且 1\lt a[1]≤a[2]≤a[3]≤…≤a[m] \lt N1<a[1]≤a[2]≤a[3]≤…≤a[m]<N。
编写一程序,输入NN,输出所有的因式分解方案。
Input
输入只有一个正整数 NN 。
Output
第 11 行至第 MM 行输出所有的 MM 种方案。(输出顺序参加样例输出)
Sample Input
#1
12
#2
100
Sample Output
#1
12=2*6
12=2*2*3
12=3*4
#2
100=2*50
100=2*2*25
100=2*2*5*5
100=2*5*10
100=4*25
100=4*5*5
100=5*20
100=10*10
Hint
100%的数据:N≤10000N≤10000。
AC代码:
#include<bits/stdc++.h>
using namespace std;
int n,k,a[10005],b[10005];
void dfs( int i,int last,int rest){
int j;
if (rest<b[i]) return;
if(i>0){
printf("%d=",n);
for (j=1; j<=i; j++) printf("%d*",b[j]);
printf("%d\n" ,rest) ;
}
for(j=last; j<=k; j++){
if (rest%a[j]==0){
b[i+1]=a[j];
dfs(i+1,j,rest/a[j]);
b[i+1]=0;
}
}
int main(){
scanf("%d",&n);
for(int i=2; i*i<=n; i++)
if(n%i==0) a[++k]=i;
dfs(0,1,n);
return 0;
原因分析:
没想到for(j=last; j<=k; j++){
if (rest%a[j]==0){
b[i+1]=a[j];
dfs(i+1,j,rest/a[j]);
b[i+1]=0;
}
}用a[i]记录n的因数
解决方案:
看视频巩固理解