Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class PerfectNumbers {
- /**
- * Program: PerfectNumbers.java
- * Creator: Chris Clarke
- * Created: 31.05.2009
- * Purpose: Calculate series of perfect numbers.
- * A perfect number means the sum of its factors add up to the number itself,
- * e.g. 6 = 1+2+3
- * The first four are: 6, 28, 496, 8128. Find some more.
- * Formula: 2^(n-1) * (2^n - 1) where n is prime - but not every prime!!
- * Modified: 13.12.2014: New improved algorithm runs in an instant.
- */
- public static boolean isPrime(int n) {
- int factors = 1; // the number itself
- int sqrt = (int) (Math.sqrt(n));
- //find factors up to square root of the number
- for (int j=1; j<=sqrt; j++)
- if (n%j==0)
- if (++factors>2)
- return false;
- //definition of prime: 2 divisors (itself and 1)
- if (factors==2)
- return true;
- return false;
- }//end isPrime()
- public static void main(String[] args) {
- for (int n=2; n<32; n++) {
- if (!isPrime(n)) continue;
- System.out.print("n="+n+"\t");
- System.out.print("2^"+(n-1)+" * (2^"+n+" - 1) \t");
- double i = Math.pow(2, n-1) * (Math.pow(2, n)-1);
- double sqr = Math.sqrt(i);
- double j;
- double sum = 1;
- for (j=2; j<=sqr; j++)
- if (i%j==0) {
- sum+=j;
- sum+=i/j;
- } // if i
- if (sum==i)
- System.out.println((long)i+" is a perfect number");
- else
- System.out.println("(number is NOT perfect)");
- }//end for n
- }//end main()
- }//end class PerfectNumbers
Advertisement
Add Comment
Please, Sign In to add comment