Hello, I'm trying to solve problem 14 from projecteuler (Longest Collatz sequence). It's my first try so probably the code or program is not good at all.
I need to check numbers from 13 to 1000000 and when I check from 13 to 100000 everything works fine except the lagg. But if I try to check from 13 to 200000 I get crash. I just cannot understand what is wrong. I would appreciate to get help with my program if possible but not an answer to this problem 14.
#include<iostream>
#include <vector>
usingnamespace std;
int collatzSequence(int num) {
vector<int> chain;
chain.push_back(num);
int temp;
while (num != 1) {
if (num % 2 == 0) {
num /= 2;
chain.push_back(num);
} elseif (num % 2 != 0) {
num = (num * 3) + 1;
chain.push_back(num);
}
}
return chain.size();
}
int main() {
int stnum = 12;
int chain = collatzSequence(12);
for (int i = 13; i < 100000; i++) { // OK
//for (int i = 1; i < 200000; i++) { // CRASH
if (collatzSequence(i) > chain) {
chain = collatzSequence(i);
stnum = i;
} elseif (i > stnum && chain == collatzSequence(i)) {
stnum = i;
}
}
cout << stnum << " " << chain;
}
- In main() you are calling your function 3 times. As this is a pretty expensive function to run, it would bee wise to run it once and store the result for future reference:
1 2 3 4 5 6 7 8
for (int i = 13; i < 100000; i++) { // OK
int collatz = collatzSequence(i);
if (collatz > chain) {
chain = collatz;
stnum = i;
} elseif (i > stnum && chain == collatz) {
stnum = i;
}
- You should probably try and use unsignedlonglong instead of int. You need to be careful with (signed) integers and the numbers you use. Often a problem that occurs onlyif a number is above a certain number it is caused by integer overflow.
Hope that helps, please do let us know if you have any further questions.