In: Computer Science
{
/* Write a program in C++ to find the perfect numbers between 1 and
500.
The perfect numbers between 1 to 500 are:
6
28
496*/
int sum = 0;
int i = 1;
int j = 1;
for (i ; i <= 100; i++)
{
for (j; j <= 100; j++)
{
if (j <
i)//Line 55
{
if (i % j ==
0)
sum = sum + j;
}
}
if (sum == i)
cout << i
<< " ";
j = 1;//line 66
sum = 0;
}
return 0;
}
Can someone please explain the code above and how it works. what is the purpose of the comparison on line 55 and I on line 66?
#include<iostream>
using namespace std;
int main()
{
int sum = 0;
int i = 1;
int j = 1;
//perfect number is equal to sum of its
divisors
//Example : number 6
//divisors of 6 are : 1,2,3 = sum of these values is
1+2+3 = 6
//below code is implement by using above logic
//Here i is the number to check,if it is perfect
number or not
for (i ; i <= 500; i++)
{
//here j is used to divide i
value
for (j; j < i; j++)
{
//This
condition used to check the value j is less than i
//We
have to find the divisor of i upto i-1 value.So we have to wrote
the condition (j<i)
//For
example i value is 6
//To check
is perfect number or not.we have to divide i value with j value and
it gives reminder zero and also some of those j values should equal
to i value
//suppose i =
6
//6%1 = reminder
0
//6%2 = reminder
0
//6%3 = reminder
0
//6%4 = remimder
2
//6%5 = remimder
1.After this the condition will fail.
if (j
< i)//Line 55
{
//This condition is used to find the number i is divisible by j are
not.Then it add the j value with sum.
//In above example,sum the value of j which got the reminder
0.
//1+2+3 = 6.So 6 is the perfect number
if (i % j == 0)
sum = sum + j;
}
}
//if sum equal to i
//At i = 6,sum will become
6.Then it prints the sum
if (sum == i)
cout
<< i << " ";
//we have to divide every
number (i)starting from 1 to i-1.But after completion of inner for
loop, j value will different not equal to 1.So we have to
initialize j value with 1 before going to outer for loop.So here it
writtern as j = 1.Otherwise from next iteration,i will not divide
from 1.
j = 1;//line 66
sum = 0;
}
return 0;
}