We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I actually did that overkill (even though we are limited to ints instead of even longs).
public int divisorSum (int N){
HashMap<Integer,Integer> primeFactorization = factor(N);
int total = 1;
for (int p:primeFactorization.keySet()) {
System.err.println("considering prime: " +p + " with mult: "+ primeFactorization.get(p));
int factor = 1;
for (int i=0;i<primeFactorization.get(p);i++) {
factor*=p;
factor+=1;
}
total*=factor;
}
return total;
}
private HashMap<Integer,Integer> factor(int n){
HashMap<Integer,Integer> mii = new HashMap<>();
if(isPrime(n)){
mii.put(n,1);
return mii;
}
if (n%2==0){
int m = n;
int cnt=0;
do{
m/=2;
cnt++;
}while(m%2==0);
mii.put(2,cnt);
}
double ceil = n/2.0;
for (int i = 3; i <= ceil; i += 2) {
if ((isPrime(i)) && (n%i == 0)) {
int m = n;
int cnt=0;
do{
m/=i;
cnt++;
}while(m%i==0);
mii.put(i,cnt);
}
}
return mii;
}
private static boolean isPrime(int num) {
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 19: Interfaces
You are viewing a single comment's thread. Return to all comments →
I actually did that overkill (even though we are limited to ints instead of even longs).