Sum of numbers from 1 to N which are in Lucas Sequence
Given a number N. The task is to find the sum of numbers from 1 to N, which are present in the Lucas Sequence.
The Lucas numbers are in the following integer sequence:
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 ......
Examples:
Input : N = 10
Output : 17
Input : N = 5
Output : 10
Approach:
- Loop through all the Lucas numbers which are less than the given value N.
- Initialize a sum variable with 0.
- Keep on adding these lucas numbers to get the required sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int LucasSum( int N)
{
int sum = 0;
int a = 2, 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 << LucasSum(N);
return 0;
}
|
Java
class GFG
{
static int LucasSum( int N)
{
int sum = 0 ;
int a = 2 , 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(LucasSum(N));
}
}
|
Python3
def LucasSum(N):
Sum = 0
a = 2
b = 1
c = 0
Sum + = a
while (b < = N):
Sum + = b
c = a + b
a = b
b = c
return Sum
N = 20
print (LucasSum(N))
|
C#
using System;
class GFG
{
static int LucasSum( int N)
{
int sum = 0;
int a = 2, 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;
Console.WriteLine(LucasSum(N));
}
}
|
PHP
<?php
function LucasSum( $N )
{
$sum = 0;
$a = 2; $b = 1; $c ;
$sum += $a ;
while ( $b <= $N )
{
$sum += $b ;
$c = $a + $b ;
$a = $b ;
$b = $c ;
}
return $sum ;
}
$N = 20;
echo (LucasSum( $N ));
?>
|
Javascript
<script>
function LucasSum(N)
{
var sum = 0;
var a = 2, 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(LucasSum(N));
</script>
|
Output:
46
Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
27 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...