c++ - Stuck in an infinite loop? (Maybe) -
i trying finish project euler problem 14 in c++ , stuck. right when run problem gets stuck @ far: number highest count: 113370 count of 155 far: number highest count when seek changing value on 113371 works. going on??
the question is:
the next iterative sequence defined set of positive integers: n → n/2 (n even) n → 3n + 1 (n odd)
using rule above , starting 13, generate next sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 can seen sequence (starting @ 13 , finishing @ 1) contains 10 terms. although has not been proved yet (collatz problem), thought starting numbers finish @ 1. starting number, under 1 million, produces longest chain?
#include<stdio.h> int main() { int limit = 1000000; int highnum, number, i; int highcount = 0; int count = 0; for( number = 13; number <= 1000000; number++ ) { = number; while( != 1 ) { if (( % 2 ) != 0 ) { = ( * 3 ) + 1; count++; } else { count++; /= 2; } } count++; printf( "so far: number highest count: %d count of %d\n", number, count ); if( highcount < count ) { highcount = count; highnum = number; } count = 0; //break; } printf( "the number highest count: %d count of %d\n", highnum, highcount ); }
you getting integer overflow. update code , see yourself:
if (( % 2 ) != 0 ) { int previ = i; = ( * 3 ) + 1; if (i < previ) { printf("oops, < previ: %d\n", i); homecoming 0; } count++; } you should alter type of i long long or unsigned long long prevent overflow.
(and yes, cache intermediate results)
c++ collatz
No comments:
Post a Comment