I am currently solving a Problem with Project Euler 14 :
The following iterative sequence is defined for a set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
Which starting number, under one million, produces the longest chain?
To solve the problem, I developed the following algorithm:
- Instead of alternately finding a series for each number that will contain a lot of redundant calculations, I try to expand the series back from 1. That is, start with a number and predict the element in front of it.
- Since multiple episodes can be generated, save the last number of all episodes using the linked list. (The idea is to store only those items that have longer rows.)
- I will loop this until I find all the numbers under the given limit; the last number under the limit will have the longest row.
Here is my code:
void series_generate(long num)
{
long n = 1;
addhead(n);
while (n < num)
{
series *p;
for (p = head; p != NULL; p = p->next)
{
long bf = p->num - 1;
if (p->num%2 == 0 && bf != 0 && bf%3 == 0) {
bf /= 3;
if (bf != 1)
addhead(bf);
if (bf < num)
n++;
}
p->num *= 2;
if ( p->num < num)
n++;
}
}
}
.
, , .
- , ?