Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- public class Test {
- // list will contain the prime factors
- static List<Integer> list = new ArrayList<>();
- static void split(int num)
- {
- // This method looks for a pair fo factors of num
- // starting from 2 and increasing.
- // The first time it finds a pair, it calls split
- // on both factors, and ends
- // It will find the smallest (and largest) factor
- for (int i=2; i<Math.sqrt(num); i++)
- {
- if (num % i ==0)
- { // i and num/i are factors of num
- split(i); // recursively split them
- split(num/i);
- return; //and finish this
- }
- }
- // if we get to here, num is prime - add it to the list
- list.add(num);
- }
- public static void main(String[] args) {
- split(120);
- for (Integer i:list)
- System.out.print(i+" "); // 2 2 2 3 5
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment