Advertisement
mhrivnak

Project Euler 14

Dec 15th, 2012
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.95 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6.     var winner, winningCount uint
  7.     var i uint
  8.     cache := make(map[uint]uint)
  9.     for i=1; i<1000000; i++ {
  10.         count := getSeqLength(i, cache)
  11.         if count > winningCount {
  12.             winningCount = count
  13.             winner = i
  14.         }  
  15.     }  
  16.     fmt.Println(winner)
  17. }
  18.  
  19. func getSeqLength(start uint, cache map[uint]uint) uint {
  20.     var count uint = 1
  21.     countValues := make(map[uint]uint)
  22.     value := start
  23.  
  24.     for value > 1 {
  25.         if cachedValue := cache[value]; cachedValue != 0 {
  26.             count += (cachedValue - 1)
  27.             break
  28.         } else if value % 2 == 0 {
  29.             value = value >> 1
  30.             count++
  31.         } else {
  32.             countValues[count] = value
  33.             value = value * 3 + 1
  34.             count++
  35.         }  
  36.     }  
  37.  
  38.     for k, v := range countValues {
  39.         cache[v] = count - k + 1
  40.     }  
  41.     return count
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement