Given a positive integer n, write an efficient function to find all prime factors of n. The output should include each prime factor the number of times it divides n.
Divide by 2: Continuously divide the number by 2 as long as it is even.
Odd factors: Start from 3 and check odd numbers up to the square root of the number to check for factors. If a number divides the current number, it is a prime factor.
Remaining number: If the remaining number after the above steps is greater than 2, it is a prime number.
publicclassPrimeFactors {
public List<Integer>primeFactors(int n) {
List<Integer> factors =new ArrayList<>();
// Check for number of 2s that divide nwhile (n % 2 == 0) {
factors.add(2);
n /= 2;
}
// Check for odd factors from 3 onwardsfor (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
// If n is still a prime number greater than 2if (n > 2) {
factors.add(n);
}
return factors;
}
publicstaticvoidmain(String[] args) {
PrimeFactors solution =new PrimeFactors();
System.out.println(solution.primeFactors(12)); // Output: [2, 2, 3] System.out.println(solution.primeFactors(16)); // Output: [2, 2, 2, 2] System.out.println(solution.primeFactors(15)); // Output: [3, 5] }
}
classPrimeFactors:
defprime_factors(self, n):
factors = []
# Check for number of 2s that divide nwhile n %2==0:
factors.append(2)
n //=2# Check for odd factors from 3 onwardsfor i in range(3, int(n**0.5) +1, 2):
while n % i ==0:
factors.append(i)
n //= i
# If n is still a prime number greater than 2if n >2:
factors.append(n)
return factors
# Example usagepf = PrimeFactors()
print(pf.prime_factors(12)) # Output: [2, 2, 3]print(pf.prime_factors(16)) # Output: [2, 2, 2, 2]print(pf.prime_factors(15)) # Output: [3, 5]