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

时间:2021-10-16 18:33:05

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

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

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

代码如下:

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, 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 {
		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分钟。