Check for perfect number
Check if the sum of all the divisors of a number brings the number itself.
Learning Objectives
- Finding divisors of an integer number.
- Finding successive sum of divisors in a loop.
Program Approach
- A divisor is found by dividing a number from 1 to half of the number value. No divisor can be more than the half of the number value. For e.g. divisor if 30 can not be more than 15 and even for 31 it can not be more than 15 as far as integer division goes.
Source Code
|
|
Run Output
Code Understanding
int s=0, mid=n/2;
s has been declared to prepare the sum of divisors.
for(int i=1;i<=mid;i++)
The loop will run till the half value of the number (mid=n/2) as no divisor of a number can be more than half of the number. This will also improve the program efficiency.
if(n%i==0) s+=i;
This is a way to find the divisors of a number as if the number is fully divided the remainder will be 0. So every divisor from 1 to half of the number value is tried. If the division yields a 0 remainder then the given number (current value of i) is a divisor. Then the divisors are successively added by using s+=i;
if (s==n) p=1;
If the sum of divisors is equal to the number itself; condition for being a perfect number we set a variable p = 1. this variable was initialized as 0 in the beginning.
if(p)
setting p=1 means that condition within if will be true. this statement can also be written as if(p==1)
Notes
This program will work for positive integers only.
Suggested Filename(s): perfect.cpp, perfectnum.cpp
Created: 2-Dec-2017 18:50 | Updated: 15-Sep-2018 13:51|
