约数的个数(如何不超时)

题目描述

输入n个整数,依次输出每个数的约数的个数

输入描述:

输入的第一行为N,即数组的个数(N<=1000)
接下来的1行包括N个整数,其中每个数的范围为(1<=Num<=1000000000)
当N=0时输入结束。

输出描述:

可能有多组输入数据,对于每组输入数据,
输出N行,其中每一行对应上面的一个数的约数的个数。

示例1

输入

5
1 3 4 6 12

输出

1
2
3
4
6

 

timelimit的代码

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

//约数:又称因数,    整除 ·没有余数 
//素数:又称质数,    除了1和自身,不能被中间内容除干净,如果有数 除干净了,他就不是素数 

int getResult(int n) {
	int cnt = 0;
	for (int i = 1; i <= n; i ++) {
		if (n % i == 0) {
			cnt ++;
		}
	}
	
	return cnt; 
}

int main() {
	int n;
	int t;
	while(cin >> n) {
		for (int i = 1; i <= n; i ++) {
			cin >> t;
			cout << getResult(t) <<endl;
		}
	}

	return 0;

}

AC的代码

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

//约数:又称因数,    整除 ·没有余数
//素数:又称质数,    除了1和自身,不能被中间内容除干净,如果有数 除干净了,他就不是素数

int getResult(int n) {
	int cnt = 0;

	int bound = sqrt(n);
	for (int i = 1; i <= bound; i ++) {
		if (n % i == 0) {
			if (i * i == n) {
				cnt += 1;
			} else {
				cnt += 2;
			}
		}
	}

	return cnt;
}



int main() {
	int n;
	int t;
	while(cin >> n) {
		for (int i = 1; i <= n; i ++) {
			cin >> t;
			cout << getResult(t) <<endl;
		}
	}

	return 0;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值