分解因数

1751:分解因数

总时间限制: 1000ms 内存限制: 65536kB
描述
给出一个正整数a,要求分解成若干个正整数的乘积,即a = a1 a2 a3 ... an,并且1 < a1 <= a2 <= a3 <= ... <= an,问这样的分解的种数有多少。注意到a = a也是一种分解.
输入
第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a (1 < a < 32768)
输出
n行,每行输出对应一个输入。输出应是一个正整数,指明满足要求的分解的种数
样例输入
2
2
20
样例输出
1
4

wrong answer:

#include<cstdio>
#include<cmath>
using namespace std;
int a[102];
int mod(int x)
{
int t = 1, i;
for(i = 2; i <= floor(sqrt(x)); i++)
if(x % i == 0)
t += mod(x / i);
return t;
}
int main()
{
int n;
scanf("%d", &n);
for(int j = 0; j < n; j++)
{
scanf("%d", &a[j]);
printf("%d
", mod(a[j]));
}
return 0;
}
 

错误答案当输入30时,2 3 5和 3 2 5和5 3 2重复,只能得5分

accepted

#include<cstdio>
using namespace std;
int a[102];
int mod(int x, int y)
{
int t = 1, i;
for(i = x; i <= floor(sqrt(y)); i++)
if(y % i == 0)
t += mod(i, y / i);
return t;
}
int main()
{
int n;
scanf("%d", &n);
for(int j = 0; j < n; j++)
{
scanf("%d", &a[j]);
printf("%d
", mod(2, a[j]));
}
return 0;
}

正确答案在函数中使用了两个参数,每次从x开始循环,而不是从2开始,避免了重复的情况

原文地址:https://www.cnblogs.com/njbw7782/p/10054221.html