I'd like to reduce the complexity of my code
Problem :
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?
Solution :
import java.util.Scanner;
import java.util.TreeSet;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
for (int i = 0; i < testCases; i++) {
int input = sc.nextInt();
System.out.println(calculateFactors(input));
}
}
public static int calculateFactors(int input) {
TreeSet<Integer> set = new TreeSet<>();
while (input % 2 == 0) {
set.add(2);
input = input / 2;
}
for (int i = 3; i < Math.sqrt(input); i = i + 2) {
while (input % i == 0) {
set.add(i);
input = input / i;
}
}
if (input > 2) {
set.add(input);
}
int max = set.last();
return max;
}
}