Advertisement
FedchenkoIhor

perfect numbers

Sep 23rd, 2016
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. public class PerfectNumbers {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.     long start = System.currentTimeMillis();
  6.  
  7.     int goal = 0;
  8.     int amount = 5;
  9.     int i = 2;
  10.    
  11.     System.out.print("The first " + amount + " perfect numbers: ");
  12.    
  13.     while (goal < amount) {
  14.         if (i == sumOfDivisors(i)) {
  15.         System.out.print(i + " ");
  16.         goal++;
  17.         }
  18.         i++;           
  19.     }
  20.     System.out.println("");
  21.  
  22.     long finish = System.currentTimeMillis();
  23.     System.out.println("Time of completion " + (finish - start) + " ms");
  24.     }
  25.  
  26.     public static double sumOfDivisors(int x) {
  27.     int result = 0;
  28.     int stop = 0;// It returns 0 if the amount is greater than the number of divisors          
  29.     for (int i = 1; i < x/2; i++) {
  30.         if (x % i == 0) {
  31.  
  32.         result += i;
  33.         if (result > x) {
  34.             return stop;
  35.         }
  36.         }
  37.     }
  38.     return result;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement