Given a natural number n (1 <= n <= 500000), please output the summation of all its proper divisors.
Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.
e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.
Input
An integer stating the number of test cases (equal to about 200000), and that many lines follow, each containing one integer between 1 and 500000 inclusive.
Output
One integer each line: the divisor summation of the integer given respectively.
Example
Sample Input:
3
2
10
20
Sample Output:
1
8
22
Writing the O(N) code is not the big deal for this(traverse till N/2)..question but writing quality code O(sqrt(n)) is efficient way to solve it.Thats why great companies used to ask such question because the wants quality code.
public static int getSumProperDivisors(int number)
{
int n=number;
int sum=1;
int numOfDiv=0;
int loop=(int)Math.sqrt(number);
for (int i=2;i<=loop;i++)
{
if(n%i == 0)
{
numOfDiv += 2;
sum += i + n/i;
}
}
if(loop*loop==n)
{
numOfDiv--;
sum -= loop;
}
return sum;
}
TC o(sqrt(n))
SC O(1)
0 comments:
Post a Comment