Home  >  Article  >  Backend Development  >  C++ code that reduces fractions to their simplest form

C++ code that reduces fractions to their simplest form

王林
王林forward
2023-09-05 19:37:061742browse

C++ code that reduces fractions to their simplest form

Given two integers Num1 and Num2 as input. These two integers can be represented as fractions Num1/Num2. The goal is to reduce this fraction to its simplest form.

Find the greatest denominator using the Greatest Common Divisor (GCD)

  • We will calculate the greatest common divisor of these two numbers.

  • Divide both numbers by their greatest common divisor.

  • Set these two variables to the quotient after division.

  • The simplest fraction will be Num1/Num2.

Example

Input - Num1=22 Num2=10

Output - Num1 = 11 Num2 = 5

The simplest fraction is: 11/5

Explanation- The greatest common divisor of 22 and 10 is 2.

22/2=11, 10/2=5

The simplest fraction is 11/5

Input- Num1=36 Num2=40

Output- Num1 = 9 Num2 = 10

The simplest fraction is: 9/10

Explanation - 36 and The greatest common divisor of 40 is 4.

40/4=10, 36/4=9

The simplest fraction is 9/10

The method used in the following program is as follows

In In this method, we first use a recursive method to calculate the greatest common divisor of the input numbers. Divide two numbers by their greatest common divisor and get the quotients, which will be part of the simplest fraction.

  • Get the input variables Num1 and Num2.

  • The function findGCD(int a, int b) accepts num1 and num2 and returns the greatest common divisor of the two.

  • If b is 0, return a, otherwise return findGCD(b,a%b).

  • The function lowestFraction(int num1, int num2) accepts two numbers as input and prints the simplest fraction.

  • Use the variable denom to represent the greatest common divisor.

  • Set num1=num1/denom and num2=num2/denom.

  • Print num1 and num2.

  • Print the simplest fraction as num1/num2.

Example

#include <bits/stdc++.h>
using namespace std;
int findGCD(int a, int b) {
   if (b == 0)
      return a;
      return findGCD(b, a % b);
   }
   void lowestFraction(int num1, int num2){
      int denom;
      denom = findGCD(num1,num2);
      num1/=denom;
      num2/=denom;
      cout<< "Num1 = " << num1<<endl;
      cout<< "Num2 = " << num2<<endl;
      cout<< "Lowest Fraction : "<<num1<<"/"<<num2;
}
int main(){
   int Num1 = 14;
   int Num2 = 8;
   lowestFraction(Num1,Num2);
   return 0;
}

Output

If we run the above code it will generate the following output

Num1 = 7
Num2 = 4
Lowest Fraction : 7/4

The above is the detailed content of C++ code that reduces fractions to their simplest form. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete