go 斐波那契

假装没事ソ 提交于 2020-03-25 15:48:18

3 月,跳不动了?>>>

用go 求解fib比较效率

 

 

 

go可以求解到45项都很快

package main

import (
	"fmt"
	"time"
)

func Fib(n int) int {
	if n < 2 {
		return n
	}
	return Fib(n-1) + Fib(n-2)
}

func single(size int) (int64, []int) {
	st := time.Now().Unix()
	ans := make([]int, size)

	for i := 0; i < size; i++ {
		ans[i] = Fib(i)
	}
	ed := time.Now().Unix()
	return ed - st, ans
}

func FibMul(n int, c chan int) {
	c <- Fib(n)
}
func Multiple(size int) (int64, []int) {
	st := time.Now().Unix()
	ans := make([]int, size)
	c := make(chan int, size)

	for i := 0; i < size; i++ {
		go FibMul(i, c)
	}


	for i := 0; i < size; i++ {
		ans[i] = <-c
	}
	ed := time.Now().Unix()
	return ed - st, ans
}
func main() {
	size := 45
	t1, ans1 := single(size)
	t2, ans2 := Multiple(size)
	fmt.Println(t1, ans1)
	fmt.Println(t2, ans2)
}

 

基本上能快一倍  5s 比js20多s快多了

11 [0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733]
5 [0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 1597 2584 4181 6765 987 17711 10946 75025 28657 46368 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733]

 

 

js

function fib(n) {
    return n < 2 ? n : fib(n - 1) + fib(n - 2)
}

let ans = []
let st = +new Date()
for (let i = 0; i < 45; i++)
    ans.push(fib(i))
let ed = +new Date()
console.log(ed - st, ans)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!