Jan 5, 2019 at 8:58pm UTC
I made a function to help solve problem 122 on Project Euler. When I run it on just a single number such as 35, it outputs 7; however, when the function is called in the for loop the return value changes to eight.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include <iostream>
#include <vector>
#include <cmath>
int m(int );
bool isPrime(int );
std::vector<int > primes;
int main()
{
//Prints 7
std::cout << m(35) << '\n' ;
//Will print 8 for 35
for (int i = 1; i < 201; i++)
std::cout << i << '\t' << m(i) << '\n' ;
return 0;
}
int m(int k)
{
if (k == 1)
return 0;
else if (k == 2)
return 1;
std::vector<int > prods;
prods.push_back(1);
int sum = 1, count = 0;
if (k % 2 != 0)
{
count += 2;
prods.push_back(2);
prods.push_back(3);
sum = 3;
for (int i = k / 3; i > 3; i--)
{
if (k % i == 0 && isPrime(i))
{
while (sum < i)
{
sum += 2;
count++;
prods.push_back(sum);
}
break ;
}
}
}
while (sum != k)
{
int index = prods.size() - 1;
while (sum + prods.at(index) > k)
index--;
count++;
sum += prods.at(index);
prods.push_back(sum);
}
return count;
}
bool isPrime(int x)
{
for (int i = 2; i < sqrt(x); i++)
{
if (x % i == 0)
return false ;
}
return true ;
}
Last edited on Jan 5, 2019 at 9:03pm UTC
Jan 5, 2019 at 9:06pm UTC
Could it be a problem with my compiler than? I ran it on cpp.sh and did get seven both times but still get the eight on Visual Studio
Jan 5, 2019 at 9:11pm UTC
Last edited on Jan 5, 2019 at 9:15pm UTC
Jan 5, 2019 at 9:16pm UTC
I just deleted the project and then created a new one. I copied the code over yet the problem persists.
Jan 5, 2019 at 11:13pm UTC
Well, everything I try it on produces 7 and 7.
So, sorry, can't reproduce your findings anywhere.
Jan 7, 2019 at 12:07pm UTC
Step through your code in a debugger. That will allow you to look at what the values of the variables are at each step of execution, which should help you identify why you're not getting the results you expect.