Monday, November 28, 2016

Abundant Number - GeeksforGeeks

Abundant Number - GeeksforGeeks
A number n is said to be Abundant Number if sum of all the proper divisors of the number denoted by sum(n) is greater than the value of the number n. And the difference between these two values is called the abundance.
Mathematically, if below condition holds the number is said to be Abundant number:

```sum(n)> n
abundance =  sum(n) - n
sum(n): aliquot sum - The sum of all proper divisors of n```
Given a number n, our task is to find if this number is Abundant number or not.
Simple solution is to iterate all the numbers from 1 to n-1 and check if the number divides n and calculate the sum. Check if this sum is greater than n or not.
Time Complexity of this approach: O(n)
Optimized Solution:
If we observe carefully, the divisors of the number n are present in pairs. For example if n = 100, then all the pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)
Using this fact we can speed up our program. While checking divisors we will have to be careful if there are two equal divisors as in case of (10, 10). In such case we will take only one of them in calculation of sum.
Subtract the number n from the sum of all divisors to get the sum of proper divisors.
Time Complexity: O(sqrt(n))
`int` `getSum(``int` `n)`
`{`
`    ``int` `sum = 0;`

`    ``// Note that this loop runs till square root`
`    ``// of n`
`    ``for` `(``int` `i=1; i<=``sqrt``(n); i++)`
`    ``{`
`        ``if` `(n%i==0)`
`        ``{`
`            ``// If divisors are equal,take only one`
`            ``// of them`
`            ``if` `(n/i == i)`
`                ``sum = sum + i;`

`            ``else` `// Otherwise take both`
`            ``{`
`                ``sum = sum + i;`
`                ``sum = sum + (n / i);`
`            ``}`
`        ``}`
`    ``}`

`    ``// calculate sum of all proper divisors only`
`    ``sum = sum - n;`
`    ``return` `sum;`
`}`

`// Function to check Abundant Number`
`bool` `checkAbundant(``int` `n)`
`{`
`    ``// Return true if sum of divisors is greater`
`    ``// than n.`
`    ``return` `(getSum(n) > n);`
`}`