Here is the code:
#include <iostream>
#include <ctype.h>
#include <iomanip>
using namespace std;
class Project3
{
public:
void factorcalc()
{
while (i<5000000){
++i;
factor = prime/i;
if (factor == (long long int)factor){
//if (modf(primeoverthree, 0) == 0){
cout << "Factor is: " << setprecision(12) << factor << endl;
cout << "Denominator is: " << setprecision(12) << i << endl;
++x;
factorarray[x] = factor;
}
else{/*empty else statement*/}
}
}
void displayfactorresults ()
{
for (x=0; x<9; ++x)
if (factorarray[x]%2 == 0 && factorarray[x]%3 == 0 && factorarray[x]%5 == 0 && factorarray[x]%7 == 0){
cout << factorarray[x] << setprecision(12) << endl;
}
}
private:
long double factor = 1;
long double prime = 600851475143;
long double i = 0;
int x = 0;
long double factorarray[9];
};
int main() {
Project3 Pro3;
Pro3.factorcalc();
Pro3.displayfactorresults();
return 0;
}
The code is in response to Project 3 on projecteuler.net. I am attempting to find the largest prime factor of 600851475143 using basic knowledge of c++ & common sense.
The error is occurring in the void displayfactorresults
function.
The compiler outputs the error message:
"invalid operands to binary expression 'long-double' & 'long-double'"
The %
remainder operator can only be applied to integer operands.
factorarray[x]
is of type long double
, a floating-point type.
Either use the fmod
function (watch out for rounding errors!) or convert the operands to an integer type.
Or, better yet, make factorarray
an array of some sufficiently large integer type in the first place. You're already assuming that the values can be converted to long long int
. Converting something to a desired type is usually not as good as using the desired type in the first place.