I'm a beginner, I'm trying to solve problem 14 of Project Euler (https://projecteuler.net/problem=14). Here is my code; Can anyone help me to figure out what I'm doing wrong?
Your mistake is to assume that all the values in the sequence will fit in an int (usually 32 bits). Try long (should be 64 bits on a 64 bit computer) or long long (guaranteed to be 64 bits on any system) instead. Even though you are starting with numbers that easily fit in 32-bits, some intermediate numbers don't.
There's no reason to store the chain. You just need a counter for the current and max sizes, and a place to store the current max starting number.
And there's no reason to count backwards (and if you do you should start at 999999 since the problem doesn't include a million). And you really should test 2 to 12 as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
constint Limit = 1000000;
int main() {
int maxi = 0, maxlen = 1;
for (int i = 2; i < Limit; ++i) {
int len = 1;
for (long n = i; n > 1; ++len)
n = n % 2 ? n * 3 + 1 : n / 2;
if (len > maxlen) {
maxlen = len;
maxi = i;
}
}
std::cout << maxi << ": " << maxlen << '\n';
}
#include <iostream>
#include <vector>
constint Limit = 1000000;
int main() {
std::vector<int> lens(Limit); // All values initialized to 0.
lens[1] = 1; // Answer for 1 is length 1.
int maxi = 1, maxlen = 1; // Initialize to the answer for 1.
for (int i = 2; i < Limit; ++i) {
int len = 0;
long n = i;
while (true) {
if (n < Limit && lens[n] != 0)
break; // Break when we find an answer in the table.
n = n % 2 ? n * 3 + 1 : n / 2;
++len;
}
len += lens[n]; // Add in answer from table.
lens[i] = len; // Store this answer in the table.
if (len > maxlen) {
maxlen = len;
maxi = i;
}
}
std::cout << maxi << ": " << maxlen << '\n';
}