I am working on Euler 14 issue: http://projecteuler.net/index.php?section=problems&id=14
I decided that the best way would be to create a vector of numbers that tracks how big the row was for that number ... for example, from 5 there are 6 steps to 1, so if I ever reach the number 5 in a series, I know that I have 6 steps and I donβt need to calculate these steps. With this idea, I encoded the following:
#include <iostream> #include <vector> #include <iomanip> using namespace std; int main() { vector<int> sizes(1); sizes.push_back(1); sizes.push_back(2); int series, largest = 0, j; for (int i = 3; i <= 1000000; i++) { series = 0; j = i; while (j > (sizes.size()-1)) { if (j%2) { j=(3*j+1)/2; series+=2; } else { j=j/2; series++; } } series+=sizes[j]; sizes.push_back(series); if (series>largest) largest=series; cout << setw(7) << right << i << "::" << setw(5) << right << series << endl; } cout << largest << endl; return 0; }
It seems to work relatively well for smaller numbers, but this special program stops at 113382. Can someone explain to me how I will understand why it hangs on this number?
Is there a way to change my algorithm to be better? I understand that I am creating duplicates using the current way that I do it: for example, a series of 3 is 3,10,5,16,8,4,2,1. Therefore, I already figured out the sizes for 10,5,16,8,4,2,1, but I will duplicate these solutions later.
Thanks for your help!
source share