In: Computer Science
The Lucas Numbers are a sequence very similar to the Fibonacci Sequence, the only difference being that the Lucas Numbers start with L0 = 2 and L1 = 1 as opposed to Fibonacci’s F0 = 0 and F1 = 1. Concretely, they are defined by L0 = 2, L1 = 1, and Ln := Ln−1 + Ln−2 for n > 1. Write a function in C++ that takes an integer argument N and returns the sum of the first N + 1 even Lucas Numbers.
The source code for the same is:
Source Code:
#include<iostream>
using namespace std;
int main()
{
int num1 = 2, num2 = 1;
int N;
int tmp;
int sum=2;
int ctr=1;
cout << "Enter N: ";
cin >> N;
while(ctr!=N+1)
{
tmp = num1 + num2;
if(tmp%2==0)
{
sum+=tmp;
ctr++;
}
num1 = num2;
num2 = tmp;
}
cout << endl << "Sum of first " << ctr << " Lucas Numbers is : " << sum;
return 0;
}
Output:
Description:
Here I took 2 variables num1 and num2 that are added to get the next number. They are initialized with 2 and 1 respectively. Now, N is used for user input. The first even number is 2, so I already added it to sum which will store final sum of even numbers. ctr is used to track how many numbers added and when it reaches N+1, the loop terminates. count is initialized with 1 as we already summed 2. Now, num1 and num2 are added in temp, checked and if it is even number, it is added in sum. Whether it is even or odd, it is used to generate next number. So, the logic is like num1 = 2, num2 =1 then temp = 3. So, after checking if 3 is even or not, num1 is assigned value of num2, num2 is assigned value of temp. So, we are moving ahead 1 step so that the next number can be generated. Here, it will give 1+3=4.
First 4 even Lucas Numbers are: 2, 4, 18, 76. So, their sum is 100. (see the output in N=3)
First 6 even Lucas Numbers are: 2, 4, 18, 76, 322, 1364. So, the sum is 1786. (output for N=5).
Do comment if there is any query. Thank you. :)