挑战CPU运算能力-寻找完美数(Perfect Numbers)
来源:互联网 发布:淘宝网禁止发布 编辑:程序博客网 时间:2024/04/27 14:25
任何一个自然数的约数中都有1和它本身,我们把小于它本身的因数叫做这个自然数的真约数。
如6的所有真约数是1、2、3,而且6=1+2+3。像这样,一个数所有真约数的和正好等于这个数,通常把这个数叫做完美数。
在编写这段代码前,没有想到完美数这么少,100以内只有6、28两个;1亿以内,也才4个。
计算1亿以内的完美数时,实在是挑战计算机的运算能力啊,两个小时没算完,在哪里能借个超级计算机用用呢?
代码如下:
package example;//JHTP Exercise 6.24: Perfect Numbers//by pandenghuang@163.com/**(Perfect Numbers) An integer number is said to be a perfect number if its factors, including1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 =1 + 2 + 3. Write a method isPerfect that determines whether parameter number is a perfect number.Use this method in an application that displays all the perfect numbers between 1 and 1000. Displaythe factors of each perfect number to confirm that the number is indeed perfect. Challenge the computingpower of your computer by testing numbers much larger than 1000. Display the results.*/import java.util.Scanner;import java.util.Date;public class PerfectNumber {public static boolean isPerfect(int number){int sum=0;for (int i=1;i<number;i++){if (number%i==0)sum+=i;}if (sum==number)return true;elsereturn false;}public static void main(String[] args){int size=0;int count=0;long beginTime=0;long endTime=0;double duration=0.0;Scanner input=new Scanner(System.in);do {System.out.print("请输入上限(整数,输入-1退出):");size=input.nextInt();if(size==-1)System.out.print("已退出程序");else{beginTime=new Date().getTime();for (int i=1;i<=size;i++){if (isPerfect(i)){System.out.printf("%d\t",i);count++;if (count%10==0)System.out.println();}}endTime=new Date().getTime();duration=(double)(endTime-beginTime)/1000/60;System.out.printf("\n%d以下的完美数共有以上%d个,共用时%.2f分钟。\n\n",size,count,duration);}}while (size!=-1);}}
运行结果:
请输入上限(整数,输入-1退出):10000
6 28 496 8128
10000以下的完美数共有以上4个,共用时0.00分钟。
请输入上限(整数,输入-1退出):100000
6 28 496 8128
100000以下的完美数共有以上8个,共用时0.34分钟。
0 0
- 挑战CPU运算能力-寻找完美数(Perfect Numbers)
- 挑战CPU运算能力2-输出十进制、二进制、八进制及十六进制对照表(Table of Binary, Octal and Hexadecimal Numbers)
- 完美数遍历(Find perfect number)
- I00035 完美数(Perfect number)
- 寻找丑数(运算)
- 寻找完美数
- 常见CPU运算能力对比
- [Leetcode] Perfect Squares 完美平方数
- POJ 1338 Ugly Numbers 寻找丑数
- leetcode 279. Perfect Squares-完美平方数|动态规划
- LeetCode-279. Perfect Squares | (JAVA) (完美平方数)
- 1218 - Perfect Service(完美服务)
- LeetCode 279. Perfect Squares(完美平方)
- SAM得到完美匹配(perfect match)
- LeetCode 507 Perfect Number(完美数字)
- perfect numbers( WA!)
- (挑战编程_7_2)Carmichael Numbers
- (挑战编程_7_6)Smith Numbers
- 团体程序设计天梯赛-练习集 L2-008. 最长对称子串
- gitlab 设置发送邮件邮箱
- 7z - Ubuntu
- 省市县json
- centos安装gcc
- 挑战CPU运算能力-寻找完美数(Perfect Numbers)
- 为什么使用sigaction而非signal
- 根据进程名杀死进程 -kill进程名
- 查询Android UA String
- vs2012 MFC连接及操作access(2007)数据库(ADO)
- 使用思维宫殿记忆TCP分层结构
- 用XCA(X Certificate and key management)可视化程序管理SSL 证书(2)--生成SSL证书请求
- 安卓四大控件之Activity详解
- 使用优先队列实现游戏公告模块(Java)