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.
publicintdivisorSum(intn){intsum=0;intsqrt=(int)Math.sqrt(n);// Small optimization: if n is odd, we can't have even numbers as divisorsintstepSize=(n%2==1)?2:1;for(inti=1;i<=sqrt;i+=stepSize){if(n%i==0){// if "i" is a divisorsum+=i+n/i;// add both divisors}}// If sqrt is a divisor, we should only count it onceif(sqrt*sqrt==n){sum-=sqrt;}returnsum;}
Day 19: Interfaces
You are viewing a single comment's thread. Return to all comments →
Efficient O(n^(1/2)) solution
From my HackerRank solutions.
Runtime: O(n^(1/2))
Space Complexity: O(1)