簡體   English   中英

在斐波那契數列中求偶數項之和

[英]Finding the sum of even valued terms in Fibonacci sequence

#!/usr/bin/python2

"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""

odd, even = 0,1
total = 0
while True:
    odd = odd + even  #Odd
    even = odd + even     #Even
    if even < 4000000:
        total += even
    else:
        break
print total

我的算法:

  1. 如果我將前 2 個數字作為 0, 1; 我在while循環中首先找到的數字將是奇數,也是斐波那契數列的第一個。
  2. 這樣我計算偶數並每次將偶數的值加到總數中。
  3. 如果even的值大於 4e6,我將退出無限循環。

我已經嘗試了很多,但我的答案總是錯誤的。 谷歌搜索說答案應該是4613732但我似乎總是得到5702886

基本上你在這里做的是添加斐波那契數列的每第二個元素,而問題只要求對偶數元素求和。

你應該做的只是迭代所有低於 4000000 的斐波那契值並執行if value % 2 == 0: total += value %是除法運算符的余數,如果除以 2 的余數等於 0,則該數字為偶數。

例如:

prev, cur = 0, 1
total = 0
while True:
    prev, cur = cur, prev + cur
    if cur >= 4000000:
        break
    if cur % 2 == 0:
        total += cur
print(total)

這是C中的簡單解決方案:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i=1,j=1,sum=0;
    while(i<4000000)
    {
    i=i+j;
    j=i-j;
    if(i%2==0)
    sum+=i;
    }
printf("Sum is: %d",sum);

}
def fibonacci_iter(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

print sum(a for a in fibonacci_iter(4e6) if not (a & 1))

您的代碼包括所有其他術語,而不是偶數值 要查看發生了什么, print eventotal += even之前print even - 您會看到奇數。 您需要做的是使用模運算符檢查您添加到總數中的數字是否均勻:

total = 0
x, y = 0, 1
while y < 4000000:
    x, y = y, x + y
    if x % 2:
        continue
    total += x

print total

你只是誤解了偶數序列和偶數值。

示例:1、2、3、5、8、13、21

在上面的序列中,我們需要選擇1, 3, 5, 13, 21而不是2, 5, 13

這是JAVA的解決方案

 public static void main(String[] args) {
        int sum = 2;    // Starts with 1, 2: So 2 is added
        int n1=1;
        int n2=2;
        int n=0;

        while(n<4000000){
            n=n1+n2;
            n1=n2;
            n2=n;
            if(n%2==0){
                sum=sum+n;
            }
        }
        System.out.println("Sum: "+sum);
    }

輸出是,

總和:4613732

def fibLessThan(lim):
    a ,b = 1,2
    total = 0
    while b<lim:
        if b%2 ==0:
            total+=b
        a,b = b,a+b
    return total

我試過這個完全有效的答案。 我們大多數人都在 fib 公式之后添加數字,而我們缺少 2。使用我的代碼,我先添加 2,然后添加 fib 公式。 這就是歐拉問題的確切答案。

python3中的代碼:

sum = 2
a = 1
b = 2
c = 0

while c <= 4000000:
    c = a + b
    if c%2 == 0:
        sum += c

    a,b = b,c

print(sum)

輸出 >>> 4613732

這是Project Euler系列的第二個問題。

事實證明,每三個斐波那契數都是偶數(最初零不是該系列的一部分)。 所以我從 a, b, c 開始是 0,1,1 並且總和將是我迭代中每個重復出現的第一個元素。 我的變量的值將被更新,每個值都是前兩個的總和:
a = b + c , b = c + a , c = a + b

變量a將始終是偶數。 這樣我就可以避免奇偶校驗。

在代碼中:


def euler2():
    a, b, c, sum = 0, 1, 1, 0
    while True:
        print(a, b, c)
        a, b, c = (b + c), (2 * c + b), (2 * b + 3 * c)
        if a >= 4_000_000:
            break
        sum += a
    return sum

print(euler2())

不確定您的問題是否已經得到解答,或者您是否找到了解決方案,但這就是您做錯的地方。 該問題要求您找到偶數值項,這意味着您需要找到斐波那契數列中可以除以 2 且沒有余數的每個值。 該問題不要求您找到每個偶數索引值。 這是您的問題的解決方案,它給出了正確的答案:

i = 1
total = 0
t = fib(i)
while t <= 4000000:
    t = fib(i)
    if t % 2 == 0:
        total += t
    i += 1
print total

基本上,您循環遍歷斐波那契數列中的每個值,通過使用“mod”(% 運算符)來檢查值是否為偶數以獲取余數,然后如果是偶數,則將其添加到總和中。

這是我如何使用本機 javascript 解決這個問題。

var sum = 0,
x = 1,
y = 2,
z = 0;
while (z < 4000000) {
    if (y%2==0){
        sum +=y;
    }
    z = x + y;
    x = y;
    y = z;
} console.log(sum);

我做了不同的事情。

def fibLessThan(lim):

    #################
    # Initial Setup #
    #################
    fibArray=[1, 1, 2]
    i=3


    #####################
    # While loop begins #
    #####################
    while True:
        tempNum = fibArray[i-2]+fibArray[i-1]
        if tempNum <= lim:
            fibArray.append(tempNum)
            i += 1
        else: 
            break

    print fibArray
    return fibArray 


limit =  4000000
fibList = fibLessThan(limit) 


#############
# summation #
#############
evenNum = [x for x in fibList if x%2==0]
evenSum = sum(evenNum)
print "evensum=", evenSum

這是我的 Python 代碼:

even_sum = 0
x = [1, 1] # Fibonacci sequence starts with 1,1...

while (x [-2] + x [-1]) < 4000000: # Check if the coming number is smaller than 4 million
    if (x [-2] + x [-1]) % 2 == 0: # Check if the number is even
        even_sum += (x [-2] + x [-1])
    x.append (x [-2] + x [-1]) # Compose the Fibonacci sequence
print (even_sum)

雖然很難相信一個有 17 個答案的問題還需要另一個答案,但在我看來,幾乎所有以前的答案都有問題:首先,他們使用模運算符 (%) 又名除法來解決加法問題; 其次,他們計算序列中的所有數字並扔掉奇數; 最后,它們中的許多看起來像C程序,幾乎沒有使用 Python 的優點。

由於我們知道斐波那契數列的每三個數字都是偶數,我們可以從 2 開始生成每三個數字並對結果求和:

def generate_even_fibonacci(limit):
    previous, current = 0, 2

    while current < limit:
        yield current

        previous, current = current, current * 4 + previous

print(sum(generate_even_fibonacci(4_000_000)))

輸出

> python3 test.py
4613732
>

這么簡單的系列有這么多代碼。 可以很容易地證明 f(i+3) = f(i-3) + 4*f(i) 所以你可以簡單地從 0,2 開始,即 f(0),f(3) 並直接通過與普通系列一樣,偶數值跨度為 3:

s,a,b = 0,0,2
while a <= 4000000: s,a,b = s+a,b,a+4*b
print(s)

我是這樣解決的:

list=[1, 2]
total =2
while total< 4000000:
    list.append(list[-1]+list[-2])
    if list[-1] % 2 ==0:
        total += list[-1]
print(total)

第一個錯誤是你弄亂了斐波那契數列,從 0 和 1 開始,而不是 1 和 2。因此總和應該初始化為 2

#!/usr/bin/python2
firstNum, lastNum = 1, 2
n = 0
sum = 2  # Initialize sum to 2 since 2 is already even
maxRange = input("Enter the final number")
max = int(maxRange)

while n < max:
    n = firstNum + lastNum
    firstNum = lastNum
    lastNum = n

    if n % 2 == 0:
        sum = sum + n

print(sum)

我是這樣做的:)

它工作得很好:)

n = int(input())
f = [0, 1]
for i in range(2,n+1):
    f.append(f[i-1]+f[i-2])
sum = 0
for i in f:
    if i>n:
        break
    elif i % 2 == 0:
        sum += i
print(sum)

這里有很多很棒的答案。 沒有人發布遞歸解決方案,所以這是 C 中的一個

#include <stdio.h>

int filt(int n){
    return ( n % 2 == 0);
}

int fib_func(int n0, int n1, int acc){
    if (n0 + n1 > 4000000)
        return acc;
    else
        return fib_func(n1, n0+n1, acc + filt(n0+n1)*(n0+n1));
}       

int main(int argc, char* argv){
    printf("%d\n", fib_func(0,1,0));
    return 0;
}

它應該是:

odd, even = 1,0

此外,每三個數字是偶數(偶數 + 奇數 + 奇數 = 偶數)。

如果您添加斐波那契數列的第二個值,您將獲得最后一個添加值之后的下一個斐波那契值。 例如:

f(0) + f(2) + f(4) = f(5)
0 + 1 + 3 + 8 = 13

但是您的代碼目前沒有添加第一個偶數值1

其他答案是正確的,但請注意,要在數組中添加所有偶數,只需執行 myarray=[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

sum(map(lambda k:k if k%2 else 0, myarray))

要么

sum([k if k%2 else 0 for k in [1,2,3,4,5]])

斐波那契數列中的每第三項都是偶數。 所以,你可以有這個:

prev, cur = 0, 1
count = 1
total = 0
while True:
    prev, cur = cur, prev + cur
    count = count + 1
    if cur >= 4000000:
        break
    if count % 3 == 0:
        total += cur
print(total)

或者這個(盡可能少地改變你的代碼):

even, odd = 0,1                       # this line was corrected
total = 0
while True:
    secondOdd = even + odd                   # this line was changed
    even = odd + secondOdd     #Even         # this line was changed
    if even < 4000000:
        total += even
        odd = secondOdd + even               # this line was added
    else:
        break
print total

另一種方法是(通過使用一些簡單的數學)檢查a2+a5+a8+a11+...+a(3N+2) (偶數斐波那契值的總和a2+a5+a8+a11+...+a(3N+2)的總和是否等於(a(3N+4)-1)/2 因此,如果您可以直接計算該數字,則無需計算所有先前的斐波那契數。

代碼中的問題基本上與循環樣式和檢查條件計時有關。 使用以下用 Java 編碼的算法,您可以找到 (second + first) < 4000000 條件檢查,它為您帶來正確的(小於 4000000)結果,有一個很好的編碼...

   int first = 0, second = 1, pivot = 0;

    do {

        if ((second + first) < 4000000) { // this is the point which makes your solution correct
          pivot = second + first;
          first = second;
          second = pivot;
          System.out.println(pivot);
        } else {
            break;
        }


    } while (true);

這是python實現並且完美運行。

from math import pow
sum=0
summation=0
first,second=1,2
summation+=second
print first,second,
while sum < 4*math.pow(10,6):
     sum=first+second
     first=second
     second=sum
     #i+=1
     if sum > 4*math.pow(10,6):
        break
     elif sum%2==0:
        summation+=sum
print "The final summation is %d" %(summation)
        long sum = 2;
        int start = 1;
        int second = 2;
        int newValue = 0;
        do{
            newValue = start + second;
            if (newValue % 2 == 0) {
                sum += newValue;
            }
            start = second;
            second = newValue;
        } while (newValue < 4000000);
        System.out.println("Finding the totoal sum of :" + (sum));`enter code here`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM