#include <iostream>
int ifReturnPerfectOrZero(int iX)
{
int iSum = 0;
for (int iChecker = 1; iChecker < iX ; ++iChecker)
{
if (iX%iChecker == 0)
{
iSum = iSum + iChecker;
}
if (iX == iSum)
{
return iX;
}
}
return 0;
}
int main()
{
std::cout << "Enter limit (from zero to)" << std::endl;
int iLim = 0;
int Passer = 0;
std::cin >> iLim;
int iaPerfectNums[50];
for (int iX = 1; iX < iLim; ++iX)
{
Passer = ifReturnPerfectOrZero[iX];
iaPerfectNums[(iX-1)] = Passer;
}
std::cout << "The perfect numbers in the given range are:"for (int iNum = 0; iNum < iLim; ++ iNum)
{
if(iaPerfectNums[iNum] != 0)
{
std::cout << iaPerfectNums[iNums] << std::endl;
}
}
}
Basically, what it does is it first asks for the limit, then checks each number from 1 to LIM if its a perfect number (a number that is equal to the sum of its divisors), if it is it adds it to iaArray, if its not it just adds in 0 to the array. When it reaches the LIM, it checks all of iaArrays values, if its a 0, it doesn't do anything, if its anything other than zero, it couts it.
#include <iostream>
usingnamespace std;
int isperfect(int n){
int sum = 0;
for(int i = 1; i <= n/2;i++)
if(n % i == 0)
sum+=i;
if(sum == n)
return 1; // true
elsereturn 0; // false
}
int main ()
{
cout << "Enter max num : ";
int max = 0;
cin >> max;
for (int i = 1; i < max; ++i)
if(isperfect(i))
cout << i << '\n';
}
You can make return data type of isperfect() bool.
The question says finds and states all perfect numbers in given range so I didn't store it in an array. :p