Data Algorithms (language: Java) Describe what each function does and its Big O? import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.*; public class HW04 { public static boolean checkPrimeNumber(int n){ for(int i = 2; i <= n / 2; i++) if(n % i == 0) return false; return true; } public static List> multiSum(int n) { if(n <= 0){ throw new NumberFormatException("Not supported yet."); } List> p = new ArrayList<>(); p.add(Arrays.asList(1,n)); for(int i = n - 1; i >= Math.sqrt(n); i--){ if(n % i == 0){ int left = n / i; p.add(Arrays.asList(i, left)); if(! checkPrimeNumber(i)) { List> lst = multiSum(i); for(int k = 1; k < lst.size();k++) { List currList = new ArrayList<>(); currList.add(left); for(int j = 0; j < lst.get(k).size(); j++) { currList.add(lst.get(k).get(j)); } p.add(currList); } } } } for(int i = 0; i < p.size(); i++) { Collections.sort(p.get(i)); } LinkedHashSet> set = new LinkedHashSet<>(); for(int i = 0; i < p.size(); i++) { set.add(p.get(i)); } p.clear(); for(List list: set) { p.add(list); } return p; } public static void main(String[] args){ int n = 16; System.out.print("Expected result for " + n + ":\n" + " [[1,16], [2,8], [2,2,4], [2,2,2,2], [4,4]]\n"); System.out.print("A total number of unique results found: 5\n"); System.out.print("------------------------\n"); System.out.print("Actual result for " + n + ": " + multiSum(n)); } }
Data
Describe what each function does and its Big O?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.*;
public class HW04 {
public static boolean checkPrimeNumber(int n){
for(int i = 2; i <= n / 2; i++)
if(n % i == 0)
return false;
return true;
}
public static List<List<Integer>> multiSum(int n) {
if(n <= 0){
throw new NumberFormatException("Not supported yet.");
}
List<List<Integer>> p = new ArrayList<>();
p.add(Arrays.asList(1,n));
for(int i = n - 1; i >= Math.sqrt(n); i--){
if(n % i == 0){
int left = n / i;
p.add(Arrays.asList(i, left));
if(! checkPrimeNumber(i)) {
List<List<Integer>> lst = multiSum(i);
for(int k = 1; k < lst.size();k++) {
List<Integer> currList = new ArrayList<>();
currList.add(left);
for(int j = 0; j < lst.get(k).size(); j++) {
currList.add(lst.get(k).get(j));
}
p.add(currList);
}
}
}
}
for(int i = 0; i < p.size(); i++) {
Collections.sort(p.get(i));
}
LinkedHashSet<List<Integer>> set = new LinkedHashSet<>();
for(int i = 0; i < p.size(); i++) {
set.add(p.get(i));
}
p.clear();
for(List<Integer> list: set) {
p.add(list);
}
return p;
}
public static void main(String[] args){
int n = 16;
System.out.print("Expected result for " + n + ":\n" + " [[1,16], [2,8], [2,2,4], [2,2,2,2], [4,4]]\n");
System.out.print("A total number of unique results found: 5\n");
System.out.print("------------------------\n");
System.out.print("Actual result for " + n + ": " + multiSum(n));
}
}
Step by step
Solved in 4 steps with 4 images