c++ - Trying to print first 5 perfect numbers using Euler's theorem -
euler theorem states equation results perfect number if right side (2^n -1) prime number.
2^(n-1) * (2^n -1)
my code trying generate first 5 perfect numbers being : 6,28,496.8128 etc... upon execution prints numbers of euler's equation different n values (1,2,3,4 etc..). seems there mistake prime condition. can ?
so 6,28,120,496,2016 etc... result
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main(void) { (int = 2; i<100; i++) { bool prime = true; (int j = 2; j*j <= i; j++) { if (pow(2,i) - 1 % j == 0) { prime = false; } } if (prime = true) { cout << pow(2, - 1)*(pow(2, i) - 1) << " "; } } return 0; }
in if condition have
if (prime = true)
the =
operator assignment operator. evaluates true
on every iteration in case. should using ==
operator. instead should have
if (prime == true)
also, inner for
loop should run until sqrt
of (pow(2, i) - 1)
. right test if numbers i
prime. instead, make it
for (int j = 2; j*j <= pow(2,1)-1; j++)
now, iterate on numbers until square root of desired value (the "right side" of euler's theorem).
sorry edits , additions, also: in first if
statement, think expression have not produce desired results, because of order of operations. in c++, %
operand has higher precedence +/-, in expression
pow(2,i) - 1 % j == 0
1 % j
evaluated first, subtraction carried out. again, not produce desired results. natural solution place parentheses around expression, so:
(pow(2,i) - 1) % j == 0
but think might create sort of "invalid operands" error, since left side of type double
or float
, , right int
. safe, cast int:
(int)(pow(2,i) - 1) % j == 0
Comments
Post a Comment