挑战CPU运算能力-寻找完美数(Perfect Numbers)

任何一个自然数的约数中都有1和它本身,我们把小于它本身的因数叫做这个自然数的真约数。
如6的所有真约数是1、2、3,而且6=1+2+3。像这样,一个数所有真约数的和正好等于这个数,通常把这个数叫做完美数。

在编写这段代码前,没有想到完美数这么少,100以内只有6、28两个;1亿以内,也才4个。

计算1亿以内的完美数时,实在是挑战计算机的运算能力啊,两个小时没算完,在哪里能借个超级计算机用用呢?
--------------------------------------------------------------------------------------

2018年12月21日补记:

源码修改了一点小bug。

--------------------------------------------------------------------------------------

代码如下:

package exercises.ch6Methods.e6_24PerfectNumber;

//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, including
1 (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. Display
the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing
power 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;
		else
			return 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 {
		count=0; //计数器清零
		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;
			System.out.printf("\n%d以下的完美数共有以上%d个,共用时%.2f秒。\n\n",size,count,duration);
			
	}
	}
	while (size!=-1);
	
	input.close();
}
}

 

运行结果:

请输入上限(整数,输入-1退出):1000
6    28    496    
1000以下的完美数共有以上3个,共用时0.02秒。

请输入上限(整数,输入-1退出):10000
6    28    496    8128    
10000以下的完美数共有以上4个,共用时0.17秒。

请输入上限(整数,输入-1退出):100000
6    28    496    8128    
100000以下的完美数共有以上4个,共用时16.40秒。

请输入上限(整数,输入-1退出):100000
6    28    496    8128    
100000以下的完美数共有以上4个,共用时15.82秒。

请输入上限(整数,输入-1退出):-1
已退出程序



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值