brilliant_moves

PerfectNumbers.java

Dec 13th, 2014
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.45 KB | None | 0 0
  1. public class PerfectNumbers {
  2.  
  3.     /**
  4.     *   Program:    PerfectNumbers.java
  5.     *   Creator:    Chris Clarke
  6.     *   Created:    31.05.2009
  7.     *   Purpose:    Calculate series of perfect numbers.
  8.     *           A perfect number means the sum of its factors add up to the number itself,
  9.     *           e.g. 6 = 1+2+3
  10.     *           The first four are: 6, 28, 496, 8128.  Find some more.
  11.     *           Formula: 2^(n-1) * (2^n - 1) where n is prime - but not every prime!!
  12.     *   Modified:   13.12.2014: New improved algorithm runs in an instant.
  13.     */
  14.  
  15.     public static boolean isPrime(int n) {
  16.         int factors = 1;    // the number itself
  17.         int sqrt = (int) (Math.sqrt(n));
  18.  
  19.         //find factors up to square root of the number
  20.         for (int j=1; j<=sqrt; j++)
  21.             if (n%j==0)
  22.                 if (++factors>2)
  23.                     return false;
  24.  
  25.         //definition of prime: 2 divisors (itself and 1)
  26.         if (factors==2)
  27.             return true;
  28.         return false;
  29.  
  30.     }//end isPrime()
  31.  
  32.     public static void main(String[] args) {
  33.         for (int n=2; n<32; n++) {
  34.             if (!isPrime(n)) continue;
  35.  
  36.             System.out.print("n="+n+"\t");
  37.             System.out.print("2^"+(n-1)+" * (2^"+n+" - 1) \t");
  38.  
  39.             double i = Math.pow(2, n-1) * (Math.pow(2, n)-1);
  40.             double sqr = Math.sqrt(i);
  41.             double j;
  42.             double sum = 1;
  43.  
  44.             for (j=2; j<=sqr; j++)
  45.                 if (i%j==0) {
  46.                     sum+=j;
  47.                     sum+=i/j;
  48.                 } // if i
  49.  
  50.             if (sum==i)
  51.                 System.out.println((long)i+" is a perfect number");
  52.             else
  53.                 System.out.println("(number is NOT perfect)");
  54.         }//end for n
  55.     }//end main()
  56.  
  57. }//end class PerfectNumbers
Advertisement
Add Comment
Please, Sign In to add comment