九度题目1087:约数的个数
来源:互联网 发布:下载pplive网络电视 编辑:程序博客网 时间:2024/05/19 23:03
原博客地址:http://blog.csdn.net/acmman/article/details/26164239
题目1087:约数的个数
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:5459
解决:1642
题目描述:
输入n个整数,依次输出每个数的约数的个数
输入:
输入的第一行为N,即数组的个数(N<=1000)
接下来的1行包括N个整数,其中每个数的范围为(1<=Num<=1000000000)
当N=0时输入结束。
输出:
可能有多组输入数据,对于每组输入数据,
输出N行,其中每一行对应上面的一个数的约数的个数。
样例输入:
5
1 3 4 6 12
样例输出:
1
2
3
4
6
来源:
2011年清华大学计算机研究生机试真题
技巧:分半求约数
AC代码:
[cpp] view plain copy 在CODE上查看代码片派生到我的代码片#include<stdio.h> #include<string.h> int a[1500]; int Fun(int n) { int i,sum=0; if(n==1) return 1; for(i=1;i*i<=n;i++) { if(n%i==0) { if(n/i!=i) { sum+=2; } else { sum++; } } } return sum; } int main() { int i,j,n,m; while(scanf("%d",&n)!=EOF) { for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { printf("%d\n",Fun(a[i])); } } return 0; } -----------------------------------------------------------
下面我自己写,思路当然是采用他的。
分析一下结题思路:
找Num的约数个数,最直接一定是从1遍历到n,然后计数每一个可以整除的。
无奈Num<=1000000000,因此直接遍历到num会超时。
考虑num约数的规律,若p为num的约数,则q=num/p也一定为num的约数,即p*q=num。对于每一个大于sqrt(num)的约数q,一定有一个小于sqrt(num)的约数p和他对应(p= num / q < sqrt ( num ) ) 。所以求约数时候,只要求到 sqrt ( num ),然后对每一个约数计数器加2即可。特殊的,当p=q时,计数器加1。
sqrt( n ) < 100000,时间复杂度满足1s之内。
#include <iostream>#include<string.h>#include<math.h>using namespace std;/* run this program using the console pauser or add your own getch, system("pause") or input loop */int n;int count(int n){ int ans=0; int bound=sqrt(n)+1; for(int i=1;i<bound;i++){ if(n % i == 0){ if(n/i != i){ ans+=2; }else{ ans++; } } } return ans;}int out[1500];int length=0;int main(int argc, char *argv[]) { cin>>n; while(n!=0){ length=0; while(n--){ int tmp; cin>>tmp; int ans=count(tmp); out[length++]=ans; } for(int i=0;i<length;i++){ cout<<out[i]; //if(i+1 != length) { cout<<endl; } } cin>>n; } return 0;}
0 0
- 九度题目1087:约数的个数
- 九度题目1087约数的个数
- 九度题目1087:约数的个数
- 九度 题目1087:约数的个数
- 九度OJ—题目1087:约数的个数
- 九度oj 题目1087:约数的个数
- 九度OJ 题目1087:约数的个数
- 九度 oj 题目1087:约数的个数
- 【九度OJ】题目1087:约数的个数 解题报告
- 九度OJ题目1087:约数的个数
- 题目1087:约数的个数 九度OJ
- 九度OJ 1087 约数的个数
- 九度OJ 1087 约数的个数
- 九度OJ 1087:约数的个数
- 九度-1087 约数的个数[数论]
- 九度OJ-1087:约数的个数
- 九度OJ-1087-约数的个数
- 九度OJ 1087:约数的个数
- 在dos系统,进入MySQL,操作
- Problem I: 大整数的加法运算
- 解释器模式
- H5全屏轮播图如何居中显示图片不拉伸
- 微信小程序关于函数调用的小坑
- 九度题目1087:约数的个数
- JAVA笔试题(1)
- 命令模式
- ubuntu如何通过蓝牙与手机连接上网
- gulp自动化管理精灵图
- samba问题总结windows客户端无法访问samba服务器,无法网络映射驱动器
- C# 使用WebAPI上传文件实现
- PySide+QWebView使用
- Mac版Intellij IDEA弹窗报this license XXXXXXXX has been cancelled