考研机试真题--约数的个数--清华大学

关键字:求约束个数,注意不要超时(合理使用判断条件j*j < num)
题目:
题目描述
输入n个整数,依次输出每个数的约数的个数
输入描述:
输入的第一行为N,即数组的个数(N<=1000)
接下来的1行包括N个整数,其中每个数的范围为(1<=Num<=1000000000)
当N=0时输入结束。
输出描述:
可能有多组输入数据,对于每组输入数据,
输出N行,其中每一行对应上面的一个数的约数的个数。
示例1
输入
5
1 3 4 6 12
输出
1
2
3
4
6

链接:
https://www.nowcoder.com/practice/04c8a5ea209d41798d23b59f053fa4d6?tpId=40&tqId=21334&tPage=1&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

代码:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
//    freopen("a.txt", "r", stdin);
    int n, a;
    while(cin >> n){
        for(int i = 0; i < n; ++i){
            cin >> a;
            int cnt = 1;
            for(int j = 2; j * j <= a; ++j){
                if(a % j == 0){
                    cnt += 2;
                }
            }
            if(a > 1) cnt++;
            cout << cnt << endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Void_worker/article/details/81417150