斐波那契数列中从 1 到 N 的数字之和
给定一个整数N ,任务是找出斐波那契数列中从1到N的数字之和。
前几个斐波那契数是1, 1, 2, 3, 5, 8, 13, 21, 34, ....
例子:
Input: N = 5
Output: 12
1 + 1 + 2 + 3 + 5 = 12
Input: N = 10
Output: 20
1 + 1 + 2 + 3 + 5 + 8 = 20
方法:
- 循环遍历所有小于N的斐波那契数。
- 用0初始化sum变量。
- 继续添加这些斐波那契数以获得所需的总和。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the
// required sum
int fibonacciSum(int N)
{
if (N == 0)
return 0;
// Generate all Fibonacci numbers <= N
// and calculate the sum
int sum = 0;
int a = 1, b = 1, c;
sum += a;
while (b <= N) {
sum += b;
int c = a + b;
a = b;
b = c;
}
return sum;
}
// Driver code
int main()
{
int N = 20;
cout << fibonacciSum(N);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the
// required sum
static int fibonacciSum(int N)
{
if (N == 0)
return 0;
// Generate all Fibonacci numbers <= N
// and calculate the sum
int sum = 0;
int a = 1, b = 1, c;
sum += a;
while (b <= N)
{
sum += b;
c = a + b;
a = b;
b = c;
}
return sum;
}
// Driver code
public static void main(String[] args)
{
int N = 20;
System.out.println(fibonacciSum(N));
}
}
// This code is contributed by Code_Mech.
Python3
# Python3 implementation of
# the approach
# Function to return the
# required sum
def fibonacciSum(N):
if N == 0:
return 0
# Generate all Fibonacci
# numbers <= N and calculate
# the sum
Sum = 0
a, b = 1, 1
Sum += a
while b <= N:
Sum += b
a, b = b, a + b
return Sum
# Driver code
if __name__ == "__main__":
N = 20
print(fibonacciSum(N))
# This code is contributed
# by Rituraj Jain
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the
// required sum
static int fibonacciSum(int N)
{
if (N == 0)
return 0;
// Generate all Fibonacci numbers <= N
// and calculate the sum
int sum = 0;
int a = 1, b = 1, c;
sum += a;
while (b <= N)
{
sum += b;
c = a + b;
a = b;
b = c;
}
return sum;
}
// Driver code
public static void Main()
{
int N = 20;
Console.WriteLine(fibonacciSum(N));
}
}
// This code is contributed by Code_Mech.
PHP
Javascript
输出:
33