版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37053885/article/details/88045501
约数的个数(九度教程第 56 题)
1.题目描述:
输入n个整数,依次输出每个数的约数的个数
输入描述:
输入的第一行为N,即数组的个数(N<=1000)
接下来的1行包括N个整数,其中每个数的范围为(1<=Num<=1000000000)
当N=0时输入结束。
输出描述:
可能有多组输入数据,对于每组输入数据,
输出N行,其中每一行对应上面的一个数的约数的个数。
示例1
输入
复制
5
1 3 4 6 12
输出
复制
1
2
3
4
6
2.基本思路
该问题为求解一个数x的约数个数,那么其实只需要将i在1~int(sqrt(x))+1之间遍历,求解约数个数即可,分两种情况考虑,如果 那么计数器加1,如果 && 那么计数器加2.对于每个数遍历完i之后打印计数器即可。
3.代码实现
#include <iostream>
#include <math.h>
#define N 1001
using namespace std;
int buf[N];
int getcnt(int x){
int cnt=0;
if(x==1)return 1;
int bound = sqrt(x)+1;
for(int i=1;i<bound;i++){
if(x%i==0)
if(i*i==x)cnt+=1;
else cnt+=2;
}
return cnt;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF){
for(int i=0;i<n;i++){
scanf("%d",&buf[i]);
printf("%d\n",getcnt(buf[i]));
}
}
return 0;
}
/*
输入
复制
5
1 3 4 6 12
输出
复制
1
2
3
4
6
*/