Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting odd results when trying to solve Collatz p‌r‌o‌b‌l‌e‌m
    primarykey
    data
    text
    <p>I'm trying to solving Project Euler <a href="https://projecteuler.net/problem=14" rel="nofollow noreferrer">Problem 14</a>. It asks to find the number under 1 million that generates the longest sequence. What I did was create a vector, v, and populate its elements with the length of the sequence for a particular number. Thus, the element that resides in position 13 will correspond to the length of the sequence generated by the number 13, and so on. However, some seemingly random elements take very large numbers and I can't figure out what's wrong with the code. Also, when I test it with 1,000,000, I get a completely wrong answer, but I know the program is working for some small numbers after testing them by hand and verifying.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; void find_longest(int n) { int count = 1; int max = 0; int position; vector&lt;int&gt; v; v.push_back(0); v.push_back(0); for(int i = 1; i &lt; n; i++) { long long int trainer = i; count = 1; while(trainer != 1) { if(trainer%2 == 0) { trainer /= 2; count++; } else { trainer = 3*trainer + 1; count++; } } v.push_back(count); } vector&lt;int&gt;::iterator it; for(it = v.begin(); it &lt; v.end(); it++) { cout &lt;&lt; v[*it] &lt;&lt; endl; //if(v[*it] &gt; max) //{ // max = v[*it]; // position = *it; //} } //cout &lt;&lt; "The longest sequence is " &lt;&lt; max &lt;&lt; " terms long and is "; //cout &lt;&lt; "generated by the number " &lt;&lt; position &lt;&lt; "." &lt;&lt; endl; } int main() { find_longest(100); //find_longest(1000000); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload