Jump to content
IPS Community Suite 简体中文
Sign in to follow this  
ipscn

Q2

Recommended Posts

Fibonacci序列从1和2开始,前10项的值是:

1,1,2,3,5,8,13,21,34,55,89 ......

求这个数列上值不大于四百万的偶数值的和。

支持并发的 Go语言版本

package main

import (
	"fmt"
	"strconv"
	"time"
)

func fib_V3(c chan int64, maxValue int64) {
	var n int64 = 0
	var m int64 = 1

	c <- n
	c <- m

	for {
		temp := n + m
		n = m
		m = temp

		if m > maxValue {
			close(c)
			break
		}
		c <- m
	}
}

func getEvenValuePrimeSumBelow(maxInt int64) int64 {

	var r int64 = 0
	var fibV int64 = 0
	isTrue := true
	c := make(chan int64)
	go fib_V3(c, maxInt)

	for {
		fibV, isTrue = <-c
		if !isTrue {

			break
		}
		if fibV%2 == 0 {
			r += fibV
		}

	}
	//close(c)
	return r

}

func main() {

	var maxInt int64 = 4000000

	start := time.Now()
	var r int64 = getEvenValuePrimeSumBelow(maxInt)

	fmt.Println("值不大于400万的偶数值得项得和是=>" + strconv.FormatInt(r, 10))

	fmt.Println("运行耗时:", time.Now().Sub(start))

}

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×