Sum of numbers from 1 to N which are in Fibonacci Sequence
Last Updated :
13 Mar, 2023
Given an integer N, the task is to find the sum of numbers from 1 to N which are in Fibonacci sequence.
First few Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, ….
Examples:
Input: N = 5
Output: 12
1 + 1 + 2 + 3 + 5 = 12
Input: N = 10
Output: 20
1 + 1 + 2 + 3 + 5 + 8 = 20
Approach:
- Loop through all the Fibonacci numbers which are less than N.
- Initialize a sum variable with 0.
- Keep on adding these Fibonacci numbers to get the required sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int fibonacciSum( int N)
{
if (N == 0)
return 0;
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;
}
int main()
{
int N = 20;
cout << fibonacciSum(N);
return 0;
}
|
Java
class GFG
{
static int fibonacciSum( int N)
{
if (N == 0 )
return 0 ;
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;
}
public static void main(String[] args)
{
int N = 20 ;
System.out.println(fibonacciSum(N));
}
}
|
Python3
def fibonacciSum(N):
if N = = 0 :
return 0
Sum = 0
a, b = 1 , 1
Sum + = a
while b < = N:
Sum + = b
a, b = b, a + b
return Sum
if __name__ = = "__main__" :
N = 20
print (fibonacciSum(N))
|
C#
using System;
class GFG
{
static int fibonacciSum( int N)
{
if (N == 0)
return 0;
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;
}
public static void Main()
{
int N = 20;
Console.WriteLine(fibonacciSum(N));
}
}
|
PHP
<?php
function fibonacciSum( $N )
{
if ( $N == 0)
return 0;
$sum = 0;
$a = 1; $b = 1; $c ;
$sum += $a ;
while ( $b <= $N )
{
$sum += $b ;
$c = $a + $b ;
$a = $b ;
$b = $c ;
}
return $sum ;
}
$N = 20;
echo (fibonacciSum( $N ));
?>
|
Javascript
<script>
function fibonacciSum(N)
{
if (N == 0)
return 0;
var sum = 0;
var a = 1, b = 1, c;
sum += a;
while (b <= N) {
sum += b;
var c = a + b;
a = b;
b = c;
}
return sum;
}
var N = 20;
document.write( fibonacciSum(N));
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...