题目:
大于1的正整数n可以分解为n=X1*X2*...*Xm。例如,当n=12时,共有8中不同的分解式:12=12;12=6*2;12=4*3;12=3*4;12=3*2*2;12=2*6;12=2*3*2;12=2*2*3。对于给定的正整数n,计算n共有多少种不同的分解式。
思路:
对每个因子递归搜索。以12为例,画个示意图:
然后 1+4+3 = 8,即为分解式个数。
程序如下:
// Chapter7_5.cpp : Defines the entry point for the application.
// 对于给定的正整数n,计算n共有多少种不同的分解式
// 大于1的正整数n可以分解为n=X1*X2*...*Xm。
// 例如,当n=12时,共有8中不同的分解式:12=12;12=6*2;
// 12=4*3;12=3*4;12=3*2*2;12=2*6;12=2*3*2;12=2*2*3
#include "stdafx.h"
#include<iostream>
using namespace std;
int mode = 0; //分解式个数
int count = 1; //计数变量
//求分解式个数
void funCount(int x)
{
//如果已经不能继续分解
if(x == 1)
mode++;
//如果能继续分解
else
{
for(int i=2;i<x;i++)
{
//找分解因子(从大到小)
if(x%i == 0)
{
cout << "factor is: " << x/i << endl; //输出分解因子
cout << "count: " << count++ << endl;
mode++; //分解数加1
funCount(x/i);
}
}
}
}
int main()
{
int x;
cout << "input the number: ";
cin >> x;
funCount(x);
//输出分解式个数(加1是因为该整数本身也是一种分解,函数中没有包含这种情况)
cout << "there are " << mode+1 << " decomposing mode." << endl;
system("pause");
return 0;
}
运行结果如下: