C++ 中斐波那契數平方和


斐波那契數列是一個數學數列,從 0 開始,兩個數的和等於下一個數,例如,第一個數是 0,第二個數是 1,0 和 1 的和為 1

F0=0, F1=1

Fn=Fn-1+Fn-2,
F2=F0+F1
F2=0+1
F2=1

然後當我們新增數 1 和 1 時,下一個數將是 2

F1=1, F2=1

Fn=Fn-1+Fn-2,
F3=F1+F2
F3=1+1
F3=2

斐波那契數列為 0、1、1、2、3、5、8、13、21、34、…

我們必須求燃料能級數的平方,然後對其求和並求出結果

Input :4
Output:15
Explanation:0+1+1+4+9=15
forest we will solve Fibonacci numbers till N then we will square them then at them

示例

 線上演示

#include <iostream>
using namespace std;
int main(){
   int n=4, c;
   int first = 0, second = 1, next;
   int sum =0;
   for ( c = 0 ; c < n+1 ; c++ ){
      if ( c <= 1 )
         next = c;
      else{
         next = first + second;
         first = second;
         second = next;
      }
      sum+=next*next;
   }
   printf("%d",sum );
   return 0;
}

輸出

15

更新於:2019-10-24

178 次瀏覽

開啟你的職業生涯

透過完成課程可獲得認證

開始
廣告
© . All rights reserved.