Program to find LCM of two Fibonnaci Numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers N and M. Our task is to create a program to find LCM of two Fibonacci Numbers in C++.

Problem Description − We will find the Nth and Mth Fibonacci number. And then we will find the LCM of their two numbers and return the result.

Fibonacci Numbers

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377....

Let’s take an example to understand the problem, 

Input: N = 4, B = 9

Output:

Explanation

4th Fibonacci number is 2

9th Fibonacci number is 21

LCM is 42.

Solution Approach

To solve the problem, we need to find the Fibonacci Number of N and M. Then find the LCM of the number.

Example

 Live Demo

#include <iostream>
using namespace std;
long int fibo(int N){
   long int a=0,b=1,c;
   for(int i=2; i< N;i++) {
      c=a+b;
      a=b;
      b=c;
   }
   return c;
}
int findLCM(int a, int b){
   int max, step, lcm;
   lcm = 0;
   if(a > b)
      max = step = a;
   else
      max = step = b;
   while(1) {
      if(max%a == 0 && max%b == 0) {
         lcm = max;
         break;
      }
      max += step;
   }
   return lcm;
}
int CalcFiboLCM(int N, int M) {
   int fiboN = fibo(N);
   int fiboM = fibo(M);
   return findLCM(fiboN, fiboM);
}
int main() {
   int N = 5, M = 14;
   cout<<"The LCM of two Fibonnaci number is "<<CalcFiboLCM(N, M);
   return 0;
}

Output

The LCM of two Fibonacci number is 699
raja
Published on 04-May-2020 07:46:47
Advertisements