Tuesday, May 31, 2011

WAP to Find Number of Divisor & sum of All Proper Devisor of Number Efficiently

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..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.

#include
#include
using namespace std;

int main()
{
int n;
int sum=1;
while(cin>>)
{
int numOfDiv=0;
int loop=(int)sqrt(n);

for (int i=2;i<=loop;i++)
{
if(n%i == 0)
{
numOfDiv += 2;
sum += i + n/i;
}

}

if(loop*loop==n)
{
numOfDiv--;
sum -= loop;
cout<}

cout<<"\nnumber of div are :"<cout<<"sum of proper divisors"<}


return 0;
}

TC o(sqrt(n))
SC O(1)
Run Here For Getting Sum of Divisor http://ideone.com/ElSVQ

No comments :