waltermilner

Untitled

Aug 12th, 2016
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1.  
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class Test {
  6. // list will contain the prime factors
  7.   static List<Integer> list = new ArrayList<>();
  8.  
  9.   static void  split(int num)
  10.   {
  11.     // This method looks for a pair fo factors of num
  12.     // starting from 2 and increasing.
  13.     // The first time it finds a pair, it calls split
  14.     // on both factors, and ends
  15.     // It will find the smallest (and largest) factor
  16.     for (int i=2; i<Math.sqrt(num); i++)
  17.     {
  18.       if (num % i ==0)
  19.       { // i and num/i are factors of num
  20.         split(i); // recursively split them
  21.         split(num/i);
  22.         return; //and finish this
  23.       }    
  24.     }
  25.     // if we get to here, num is prime - add it to the list
  26.     list.add(num);
  27.   }
  28.   public static void main(String[] args) {
  29.     split(120);
  30.     for (Integer i:list)
  31.       System.out.print(i+" "); // 2 2 2 3 5
  32.    
  33.   }
  34.  
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment