- 論壇徽章:
- 4
|
Problem 014:
The following iterative sequence is defined for the 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
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
問(wèn)題14:
下面是對(duì)正整數(shù)定義的操作序列:
n → n/2 (n是偶數(shù))
n → 3n + 1 (n是奇數(shù))
當(dāng)對(duì)13使用上面的規(guī)則時(shí),我們得到下面的序列:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
可以發(fā)現(xiàn)這個(gè)序列包含10個(gè)項(xiàng)。雖然還沒(méi)有被證明(Collatz問(wèn)題),但是一致認(rèn)為所有正數(shù)會(huì)收斂到1.
試找出1000000以?xún)?nèi),到達(dá)1時(shí)產(chǎn)生最長(zhǎng)序列的數(shù)是哪個(gè)。
說(shuō)明:當(dāng)序列運(yùn)算開(kāi)始之后,序列中的想允許超過(guò)1000000。
代碼:
- package main
- import (
- "fmt"
- )
- func FindCollatzPathLength(number int, knownPath map[int]int) int {
- var result int = 0
- path := make([]int, 0)
- for {
- if steps, exist := knownPath[number]; exist {
- // Update all data into knownPath
- offset := len(path)
- result = offset + knownPath[number]
- // Below steps to merge current data into record for future speed up
- for index, value := range path {
- knownPath[value] = steps + offset - index
- }
- break
- } else {
- path = append(path, number)
- if number%2 == 0 {
- // even number handling
- number = number / 2
- } else {
- // odd number handling
- number = number*3 + 1
- }
- }
- }
- return result
- }
- func Problem014(scope int) int{
- var max_steps int = 0
- var result int = 0
-
- paths := make(map[int]int)
- paths[1] = 1
- paths[2] = 2
- paths[4] = 3
-
- for number := 0; number < scope; number++ {
- steps := FindCollatzPathLength(number + 1, paths)
- if steps > max_steps {
- max_steps = steps
- result = number + 1
- }
- }
- return result
- }
- func main() {
- // There is a problem while provided number above 100000, try update code later.
- fmt.Println("Problem 014 result: ", Problem014(1000000))
- }
復(fù)制代碼 |
|