Facebook Interview Question
SDE1sCountry: United States
The cost can be difficult to compute but an upper bound could be O(nlogn) assuming that we traverse through all the primes and assume the cost of computing the number of factors given a prime is logn.
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
def computeFactors(n):
if n in primes: return [n]
factors = []
for prime in primes:
while (n % prime) == 0:
factors.append(prime)
n /= prime
if n == 1:
break
return factors
/*
Prime factors
Automatic finding of primes and then factors.
So, here, we go.
*/
def prime_factors_str( n ){
// basic stuff
upto = ceil( n ** 0.5 )
// should be pretty easily understandable
#(primes, factors) = fold( [2:upto], [ list(), list() ] ) -> {
// is my current no prime ?
pp = $.o // possible prime
#(primes,factors) = $.p
continue ( exists( primes ) :: { $.o /? pp } )
// now it is prime
primes += pp
// now, is it a factor ?
while ( pp /? n ){ n /= pp ; factors += pp }
$.p // return
}
// print factors
str ( factors , '*' )
}
println( prime_factors_str(90) )
The key to this problem is finding all the prime numbers until n and then dividing n by all the prime numbers one by one"
public class Solution {
public String getPrimeFactors(int n) {
if(n <= 3) {
return Integer.toString(n);
}
Boolean[] primes = this.getPrimes(n);
int number = n;
StringBuilder sb = new StringBuilder();
for(int i = 2; i < primes.length; i++) {
if(!primes[i] || number % i != 0) {
continue;
}
while(number % i == 0) {
sb.append(i);
sb.append(" * ");
number = number / i;
}
if(number == 1) {
break;
}
}
sb.delete(sb.length() - 3, sb.length());
return sb.toString();
}
private Boolean[] getPrimes(int n) {
if(n < 2) {
throw new IllegalArgumentException("n has to be bigger than 1");
}
Boolean result = new Boolean[n + 1];
this.initArray(result);
int prime = 2;
while(prime <= Math.sqrt(n)) {
this.checkOffNonPrimes(prime, result);
prime = this.getNextPrime(prime, result);
}
return result;
}
private void checkOffNonPrimes(int index, Boolean[] result) {
for(int i = index*index; i < result.length; i = i + index) {
result[i] = false;
}
}
private void getNextPrime(int index, Boolean[] result) {
int i = index + 1;
while(i < result.length && !result[i]) {
i++;
}
return i;
}
private void initArray(Boolean[] array) {
if(n < 2) {
throw new IllegalArgumentException("n has to be bigger than 1");
}
Arrays.fill(result, true);
array[0] = false;
array[1] = false;
}
}
geeksforgeeks.org/prime-factorization-using-sieve-olog-n-multiple-queries/
- revant June 09, 2017geeksforgeeks.org/print-all-prime-factors-of-a-given-number/