Can';我不太明白欧拉计划的问题2 我正在尝试通过一些问题来学习C++的基础知识。我已经到了…#2

Can';我不太明白欧拉计划的问题2 我正在尝试通过一些问题来学习C++的基础知识。我已经到了…#2,c++,C++,斐波那契方程中的每个新项 序列是通过添加 前两届。从1开始 第二,前10个条款为: 1、2、3、5、8、13、21、34、55、89 求所有偶数值的和 序列中不包含的术语 超过四百万 我的逻辑是: 0, 1, 1, 2, 3, 5 x y z x y z x y z x y z 以上是通过这个循环: x + y = z x = y y = z 我的代码: #include <iostream.h> using namespac

斐波那契方程中的每个新项 序列是通过添加 前两届。从1开始 第二,前10个条款为:

1、2、3、5、8、13、21、34、55、89

求所有偶数值的和 序列中不包含的术语 超过四百万

我的逻辑是:

0, 1, 1, 2, 3, 5
x  y  z
   x  y  z
      x  y  z
         x  y  z
以上是通过这个循环:

x + y = z
x = y
y = z
我的代码:

#include <iostream.h>

using namespace std;

int main()
{
    int x = 0;
    int y = 1;
    int z;
    int sum;

    for(y = 1; y <= 4000000; y++) {

          z = x + y;
          x = y;
          y = z;
            if(y % 2 == 0) {
                 sum += y;
                 }
            }
    cout << sum;
    cin.get();
}
#包括
使用名称空间std;
int main()
{
int x=0;
int y=1;
intz;
整数和;

对于(y=1;y,您使用
y
作为循环变量和序列中的第二项

你的意思是:

int x = 0;
int y = 1;
int z;
int sum = 0;

do {
    z = x + y;
    x = y;
    y = z;
    if (y % 2 == 0) sum += y;
} while (y <= 4000000);
intx=0;
int y=1;
intz;
整数和=0;
做{
z=x+y;
x=y;
y=z;
如果(y%2==0)和+=y;

}虽然(y您没有将总和初始化为零。

为了提高速度,请注意序列是偶数-奇数(重复),偶数-奇数


不需要测试每个数字就知道它是偶数还是奇数。只需添加每三个数字。

for循环代码块应该类似于

while(y <= 4000000) {
    z = x + y;
    x = y;
    y = z;
    if(y % 2 == 0) {
        sum += y;
    }
}

while(y这里有一种方法可以在O(log(N))时间内解决这个问题,而较慢的O(N)实现(O(log(N))是因为需要使用pow()函数)

首先,您需要能够在O(log(N))时间内计算第N个斐波那契数:

其中PHI=1.6180339…和PSI=-0.61803398…(查看了解更多信息)

其次,您需要计算最接近目标限额的指数(在问题2的情况下为4000000):

第三,您将使用B&Q恒等式#25(更多信息)计算偶数斐波那契数之和:

double bqIdentity25(double N)
{
    return (Fib(3*floor(N) + 2) - 1) / 2;
}
最后,计算总和:

double limit = 4000000;
double nearestIndex = nFib(limit);
double sum = bqIdentity25(nearestIndex / 3);
我们只需要每三个元素来计算偶数斐波那契数的和

希望这有帮助! 威尔

//斐波那契序列
#包括
#包括
使用名称空间std;
int main()
{
向量表;
list.clear();
列表。推回(1);
列表。推回(2);

cout它显示每个斐波那契序列号并选择偶数, 最后给出了偶数的和

 #include <stdio.h>
 #include <math.h>
 #include <time.h>
    //project euler
    //problem# 2
int main()
{
    long int a = 0;
    long int b = 1;
    long int sum = 0;
    long int f = 0;
    long int t = 1;
    long int d = 1;

  while (f <= 4000000){
  f = a + b;
  printf("   %2d. number is %7d",d,f);
  d++;
  a = b;
  b = f;
    if (f % 2 == 0){
        sum += f;
        printf("\t\t%2d. target is %7d",t,f);
        t++;
    }
  printf("\n\n");
  printf("--------------------------------------------------------------------------------");
  }
printf("\n\n\t\t\t\t\tSum of targets is %d\n\n\n", sum);
printf("--------------------------------------------------------------------------------\n");
printf("Press any key to continue...\n");
getchar();
}
#包括
#包括
#包括
//欧拉计划
//问题2
int main()
{
长整数a=0;
长整数b=1;
长整数和=0;
长整型f=0;
长整数t=1;
长整数d=1;

while(f
perl-e'$a,$b=(0,1);while($a试图对这个问题增加一些帮助。下面的程序显示了用户输入的给定长度序列的所有偶数斐波那契数列

         #include<iostream.h>
         #include<conio.h>
          class fibonacci
          {
               int input;
                        public:
                                  void series();
          };
               void fibonacci::series()
                    {
                           cout<<"enter the value";
                           cin>>input;
                           int initial=0;
                           int initial1=1;
                     for(int loop=0;loop<input;loop++)
                          { 
                             int initial2;
                             initial2=initial1+initial;
                             if(initial2%2==0)
                             {cout<<initial2<<"\t";}
                             initial=initial1;
                             initial1=initial2;
                             }
                       }
                      void main()
                                  {
                                      fibonacci a;
                                      a.series();
                                      getch();
                                   }
#包括
#包括
类斐波那契
{
int输入;
公众:
void级数();
};
void fibonacci::series()
{
库廷普特;
int初始值=0;
int initial1=1;

对于(int loop=0;loop,以下是如何在Swift中执行此操作:

/** Calculate the next even fibonacci number within a limit.

Methodology:
1) Fibonacci numbers are either odd (o) or even (e) as follows:
o, e, o, o, e,  o, o, e, o, o, e, ... because of the arithmetic
rule:
Odd + Odd = Even
Even + Even = Even
Odd + Even = Odd

2) By do two rounds of fibonacci, we can get from one "e" to the
next "e".  We don't need to bother checking its even.

3) To avoid re-computing past results, we ask for the past 
running total to be supplied, and the past pair of fibonacci 
numbers before doing our two rounds of fibonacci

4) We assume the passed in pair of fibonacci numbers don't exceed
are supplied limit, and on the next even fibonacci we can just test
for exceeding the limit there only.

5) Fibonacci numbers grow very fast (nearly doubling each time).  Since
the next even is found after two iterations, it means we have exponential
growth for the next fibonacci number.  For limit L, we'll find the sum
after O(log(L)) time.

@param  runningTotal    Total of even fibonacci numbers seen so far
@param  upperLimit      Limit number not to exceed the next even fibonacci
@param  n0              First of an adjacent pair of fibonacci numbers with
                        n0 < upperLimit
@param  n1              Next fibonacci number after n1 with n1 < upperLimit

@returns (updatedTotal,n3,n4) where updatedTotal is the supplied runningTotal
         plus the next even fibonacci number not exceeding the supplied
         upperLimit, n3 and n4 are the next pair of fibonacci numbers to be
         supplied for the next call to this method
*/
func sumNextEvenFibonacci(runningTotal:Int, upperLimit:Int, n0:Int, n1:Int) -> (Int, Int, Int)
{
    let n2 = n0 + n1
    let n3 = n2 + n1
    let n4 = n3 + n2

    if (n4 < upperLimit)
    {
        return (runningTotal + n4, n3, n4)
    }
    else
    {
        return (runningTotal, n3, n4)
    }
}

func eulerProblem_02()
{
    println("Problem 2\n\nEach 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:\n 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... \n\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n")
    var n0 = 1, n1 = 2, n2 = 0, runningTotal = 2
    do
    {
        (runningTotal, n0, n1) = sumNextEvenFibonacci(runningTotal, 4_000_000, n0, n1)
    } while (n1 < 4_000_000)
    println("The answer is \(runningTotal).\n")
}

eulerProblem_02()

下面是我们在最小循环数下的方法。如果我们用前两个数来写斐波那契级数,它是:

a、
b
,(a+b),(a+2b),
(2a+3b)
,(3a+5b),(5a+8b),
(8a+13b)
,(13a+21b),(21a+34b),
(34a+55b)

在上述系列中,
a
为1,
b
为2,突出显示的数字为偶数。在斐波那契系列中,每三个数字为偶数,序列为奇偶-奇偶-。因此,如果我们将偶数写入此系列,则为:

b,(2a+3b),(8a+13b),(34a+55b),(144a+233b).

如果我们观察这个系列中的模式,
下一个a的系数是
4*(当前a的系数)+(上一个a的系数)
。 而
下一个b的系数是
(当前a的系数)+(当前b的系数)+(下一个a的系数)

Python代码:

# Start sum with first event number
sum = 2

# Values of first two Fibonacci numbers
a = 1
b = 2

# Previous coefficient of a
prev_coef_a = 0

# Current coefficient of a and b
coef_a = 2
coef_b = 3

while ((coef_a*a)+(coef_b*b)) <= 4000000:
    print(((coef_a*a)+(coef_b*b)))
    sum += ((coef_a*a)+(coef_b*b))

    # Coefficient of a for next number
    next_coef_a = (coef_a*4)+prev_coef_a
    prev_coef_a = coef_a
    # Coefficient of b for next number
    coef_b = coef_a+coef_b+next_coef_a
    coef_a = next_coef_a

print('Sum: {}'.format(sum))

使用Kotlin的解决方案,我用这些问题来练习我的数学,并为我学习这门新语言:

import java.math.BigInteger

/**
 *
 * https://projecteuler.net/problem=2
 *
 * 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.
 *
 */
class Problem2 {

    var maxValue: Int = 4000000

    // Looking for this fibonacci value
    var fibonacci = 32
    var fibonacciValues = hashMapOf<Int, BigInteger>(0 to BigInteger.ONE, 1 to BigInteger.ONE);

    fun solution(): BigInteger {
        var solution: BigInteger = BigInteger.ZERO
        calculateFibonacci(fibonacci)

        fibonacciValues.filter {
            it.value < BigInteger.valueOf(maxValue.toLong()) &&
                    it.value.mod(BigInteger.ONE.add(BigInteger.ONE)).equals(BigInteger.ZERO)
        }.forEach {
            //println("Key: ${it.key} and ${it.value} and mv $maxValue")
            solution = solution.add(it.value)
        }

        return solution
    }

    private fun calculateFibonacci(n: Int): BigInteger? {
        if ( fibonacciValues.contains(n)) {
            return fibonacciValues.get(n)
        } else {
            val f = calculateFibonacci(n - 2)!!.add(calculateFibonacci(n - 1))

            fibonacciValues.put(n, f)
            return f
        }
    }

}
import java.math.biginger
/**
*
* https://projecteuler.net/problem=2
*
*斐波那契序列中的每个新项都是通过将前两项相加生成的。从1和2开始,前10项将是:
*
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
*通过考虑Fibonacci序列中值不超过400万的项,求偶数值项之和。
*
*/
课堂问题2{
var最大值:Int=4000000
//寻找这个斐波那契值
var fibonacci=32
var fibonacciValues=hashMapOf(0到biginger.ONE,1到biginger.ONE);
有趣的解决方案():BigInteger{
变量解决方案:biginger=biginger.ZERO
计算波那契(斐波那契)
fibonacciValues.filter{
it.value
这有点冗长,因为我添加了可测试性,如果您想查看单元测试,请看以下内容:


每三个数是偶数,所以偶数之和是(n个fib数之和)/2

但是,一些n个fib.numbers=(n+2)的项-第二项(1)


你可以从贝内特公式中得到第(n+2)项,在javascript中你可以这样求解:

function add(a, b) {
    // body...
    return a + b;
}
function fabonacci(limit) {
    var i = 2; //parseInt(limit);
    var fabonacci = [0, 1];
    var evenFab = [];
    var valToPush = 0;
    var result = [];
    while (valToPush < 4000000) {
        valToPush = fabonacci[fabonacci.length - 2] + fabonacci[fabonacci.length - 1]
        i++;
        if ((valToPush % 2) == 0) {
            evenFab.push(valToPush);
        }
        if (valToPush > 4000000 || i > limit) {
            break;
        }
        fabonacci.push(valToPush);
    }
    result['sequence'] = fabonacci;
    result['sumOfEven'] = evenFab;
    return result;
}
var result = fabonacci(10);
console.log("Fabonacci sequence:" + result['sequence']);
console.log("Sum of Even Number:" + (result['sumOfEven']).reduce(add, 0));`
功能添加(a、b){
//身体。。
/** Calculate the next even fibonacci number within a limit.

Methodology:
1) Fibonacci numbers are either odd (o) or even (e) as follows:
o, e, o, o, e,  o, o, e, o, o, e, ... because of the arithmetic
rule:
Odd + Odd = Even
Even + Even = Even
Odd + Even = Odd

2) By do two rounds of fibonacci, we can get from one "e" to the
next "e".  We don't need to bother checking its even.

3) To avoid re-computing past results, we ask for the past 
running total to be supplied, and the past pair of fibonacci 
numbers before doing our two rounds of fibonacci

4) We assume the passed in pair of fibonacci numbers don't exceed
are supplied limit, and on the next even fibonacci we can just test
for exceeding the limit there only.

5) Fibonacci numbers grow very fast (nearly doubling each time).  Since
the next even is found after two iterations, it means we have exponential
growth for the next fibonacci number.  For limit L, we'll find the sum
after O(log(L)) time.

@param  runningTotal    Total of even fibonacci numbers seen so far
@param  upperLimit      Limit number not to exceed the next even fibonacci
@param  n0              First of an adjacent pair of fibonacci numbers with
                        n0 < upperLimit
@param  n1              Next fibonacci number after n1 with n1 < upperLimit

@returns (updatedTotal,n3,n4) where updatedTotal is the supplied runningTotal
         plus the next even fibonacci number not exceeding the supplied
         upperLimit, n3 and n4 are the next pair of fibonacci numbers to be
         supplied for the next call to this method
*/
func sumNextEvenFibonacci(runningTotal:Int, upperLimit:Int, n0:Int, n1:Int) -> (Int, Int, Int)
{
    let n2 = n0 + n1
    let n3 = n2 + n1
    let n4 = n3 + n2

    if (n4 < upperLimit)
    {
        return (runningTotal + n4, n3, n4)
    }
    else
    {
        return (runningTotal, n3, n4)
    }
}

func eulerProblem_02()
{
    println("Problem 2\n\nEach 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:\n 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... \n\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n")
    var n0 = 1, n1 = 2, n2 = 0, runningTotal = 2
    do
    {
        (runningTotal, n0, n1) = sumNextEvenFibonacci(runningTotal, 4_000_000, n0, n1)
    } while (n1 < 4_000_000)
    println("The answer is \(runningTotal).\n")
}

eulerProblem_02()
Problem 2

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.

The answer is 4613732.
# Start sum with first event number
sum = 2

# Values of first two Fibonacci numbers
a = 1
b = 2

# Previous coefficient of a
prev_coef_a = 0

# Current coefficient of a and b
coef_a = 2
coef_b = 3

while ((coef_a*a)+(coef_b*b)) <= 4000000:
    print(((coef_a*a)+(coef_b*b)))
    sum += ((coef_a*a)+(coef_b*b))

    # Coefficient of a for next number
    next_coef_a = (coef_a*4)+prev_coef_a
    prev_coef_a = coef_a
    # Coefficient of b for next number
    coef_b = coef_a+coef_b+next_coef_a
    coef_a = next_coef_a

print('Sum: {}'.format(sum))
8
34
144
610
2584
10946
46368
196418
832040
3524578
Sum: 4613732
import java.math.BigInteger

/**
 *
 * https://projecteuler.net/problem=2
 *
 * 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.
 *
 */
class Problem2 {

    var maxValue: Int = 4000000

    // Looking for this fibonacci value
    var fibonacci = 32
    var fibonacciValues = hashMapOf<Int, BigInteger>(0 to BigInteger.ONE, 1 to BigInteger.ONE);

    fun solution(): BigInteger {
        var solution: BigInteger = BigInteger.ZERO
        calculateFibonacci(fibonacci)

        fibonacciValues.filter {
            it.value < BigInteger.valueOf(maxValue.toLong()) &&
                    it.value.mod(BigInteger.ONE.add(BigInteger.ONE)).equals(BigInteger.ZERO)
        }.forEach {
            //println("Key: ${it.key} and ${it.value} and mv $maxValue")
            solution = solution.add(it.value)
        }

        return solution
    }

    private fun calculateFibonacci(n: Int): BigInteger? {
        if ( fibonacciValues.contains(n)) {
            return fibonacciValues.get(n)
        } else {
            val f = calculateFibonacci(n - 2)!!.add(calculateFibonacci(n - 1))

            fibonacciValues.put(n, f)
            return f
        }
    }

}
function add(a, b) {
    // body...
    return a + b;
}
function fabonacci(limit) {
    var i = 2; //parseInt(limit);
    var fabonacci = [0, 1];
    var evenFab = [];
    var valToPush = 0;
    var result = [];
    while (valToPush < 4000000) {
        valToPush = fabonacci[fabonacci.length - 2] + fabonacci[fabonacci.length - 1]
        i++;
        if ((valToPush % 2) == 0) {
            evenFab.push(valToPush);
        }
        if (valToPush > 4000000 || i > limit) {
            break;
        }
        fabonacci.push(valToPush);
    }
    result['sequence'] = fabonacci;
    result['sumOfEven'] = evenFab;
    return result;
}
var result = fabonacci(10);
console.log("Fabonacci sequence:" + result['sequence']);
console.log("Sum of Even Number:" + (result['sumOfEven']).reduce(add, 0));`
a = 0
b = 1
c =0
sum = 0
d = 0

for s in range(4000000):    
    while(d<4000000):    
        d = a+b    
        if d%2 == 0:
        sum += d   
        print(d)    
        a = b    
        b = d


print    
print 
print("the sum is:"+str(sum))