c# - Using Cache in Collatz Sequence implementing issues -
i have created 2 lists, 1 number , 1 chain count. if number in number list, take it's chain count , add current chain count. issue right here program stucks , it's not returning me anything. problem it's solved, takes me 4.7 seconds find number under 1 million has longest sequence , chain count want optimize using cache memory.
static list<long> cache_number = new list<long>(); static list<long> cache_chains = new list<long>(); static long collatzchain(long num) { int chain = 1; while (num != 1) { if(cache_number.contains(num)){ long x = chain + cache_chains[cache_number.indexof(num)]; return x; } if (num % 2 == 0) { num = num / 2; } else { num = 3 * num + 1; } chain++; } cache_number.add(num); cache_chains.add(chain); return chain; } static void main(string[] args){ stopwatch time = new stopwatch(); time.start(); list<long> chain = new list<long>(); list<long> numbers = new list<long>(); (int = 13; < 1000000; i++) { numbers.add(i); chain.add(collatzchain(i)); } time.stop(); long elapsed = time.elapsedmilliseconds; console.writeline("the longest chain made number {0} chain of {1} elements", numbers[chain.indexof(chain.max())], chain.max()); console.write("time elapsed: {0} ms", elapsed); console.readkey(); }
Comments
Post a Comment