Hello, I am a beginner at programming and I am having some trouble finding the error in my code(pasted below). I am first trying to come up with a (1) function to evaluate integers at a given power.(2) A function to check if an integer is a perfect number. I do this by trying to use the formula N=2(k-1)*((2^k)-1). This formula only works for certain values of k so you have to do another check within the function. I look to see if the sum of the divisible numbers of the integer add up to the integer. Like 6= 1+2+3. Then I look to see if N and the sum equal each other. Note: I stop the sum of divisors once the sum becomes higher than the integer were checking.
(3) Then I make a function that will display the sum of all the divisible numbers like "6 = 1 + 2 + 3". (4) then I try to put everything together by using an infinite for loop till I find the first five perfect numbers. Can you help me see were I went wrong, Id really appreciate it.
#include <iostream>
using namespace std;
int ipow(int a, int b)
{
int i = 1, j = a;
while(i < b)
{
a = a*j;
}
if(b == 0)
{
return 1;
}
else
{
return a;
}
}
bool PerfectNumCheck(int a)
{
int sum = 0, k = 2, N = 0, b, c;
for (int i = 1; i <= (a - 1); i++)
{
if(a%i == 0)
{
sum = sum + i;
}
if(sum > a)
{
i = a;
}
}
while(N < a)
{
b = ipow(2, k - 1);
c = ipow(2, k) - 1;
N = b*c;
k++;
}
if(N == sum)
{
return 1;
}
else
{
return 0;
}
}
int ProperDivisor(int a)
{
int sum = 0;
cout << a << " = ";
for(int i = 1; i <= (a-1); i++)
{
if(a%i == 0)
{
sum = sum + i;
if(sum < a)
{
cout << i << " + ";
}
if (sum == a)
{
cout << i << endl;
i = a;
}
}
}
return 0;
}
int main(void)
{
int n = 0, check;
for (int i = 2; ; i++)
{
check = PerfectNumCheck(i);
if (check)
{
cout << i << " is a perfect number \n";
ProperDivisor(i);
cout << endl;
n++;
}
if (n == 5)
{
return 0;
}
}
}