繁体   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