Count factors of given number n.
- Difficulty Level: Easy
- Question URL: https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/count_factors/
- Time Complexity:
Solution:
Solution to Codility's problem which is from the Codility Lesson 10: Prime and composite numbers and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to count factors of given number n. You can find the question of this CountFactors problem in the Codility website.
package Codility.Lesson10;
import java.util.Arrays;
import java.util.Collections;
public class CountFactors {
public static void main(String[] args) {
// TODO Auto-generated method stub
int result2 = solution(51);
System.out.println(result2);
}
public static int solution(int N) {
// write your code in Java SE 8
int factors = 0;
int sq = (int) Math.sqrt(N);
if (Math.pow(sq, 2) != N) {
sq++;
} else {
factors++;
}
for (int i = 1; i < sq; i++) {
if (N % i == 0) {
factors += 2;
}
}
return factors;
}
}