Linkedin Interview Question
Member Technical StaffsTeam: Tools team
Country: United States
Interview Type: In-Person
public static List<Integer> factors(int num){
List<Integer> result = new ArrayList<>();
if(num == 0)
return result;
boolean isOdd = num % 2 != 0;
double limit = Math.floor(Math.sqrt(num));
int i = 1;
while(i <= limit){
if(num % i == 0){
result.add(i);
result.add(num / i);
}
i++;
if(isOdd)
i++;
}
return result;
}
public static void main(String[] args) {
System.out.println("Factors of Number: " + factors(13));
}
Simply iterate from 1 through n and n % i == 0, print the number. Elegant one liner in python below:
Test code:
- prudent_programmer March 17, 2018