📜  将分数减少到最低形式

📅  最后修改于: 2021-04-24 05:25:10             🧑  作者: Mango

给定两个整数xy ,其中x可被y整除。它可以分数x / y的形式表示。任务是将分数减小到最低形式。

例子:

Input : x = 16, y = 10
Output : x = 8, y = 5

Input : x = 10, y = 8
Output : x = 5, y = 4

方法: xy值都可以被它们的最大公约数整除。因此,如果将x和y从gcd(x,y)中除,则x和y可以简化为最简单的形式。

下面是上述方法的实现:

C++
// C++ program to reduce a fraction x/y 
// to its lowest form
  
#include 
using namespace std;
  
// Function to reduce a fraction to its lowest form
void reduceFraction(int x, int y)
{
    int d;
    d = __gcd(x, y);
  
    x = x / d;
    y = y / d;
  
    cout << "x = " << x << ", y = " << y << endl;
}
  
// Driver Code
int main()
{
    int x = 16;
    int y = 10;
  
    reduceFraction(x, y);
  
    return 0;
}


Java
// Java program to reduce a fraction x/y 
// to its lowest form 
class GFG 
{
  
// Function to reduce a fraction to its lowest form 
static void reduceFraction(int x, int y) 
{ 
    int d; 
    d = __gcd(x, y); 
  
    x = x / d; 
    y = y / d; 
  
    System.out.println("x = " + x + ", y = " + y); 
} 
  
static int __gcd(int a, int b) 
{ 
    if (b == 0) 
        return a; 
    return __gcd(b, a % b); 
      
}
  
// Driver Code 
public static void main(String[] args)
{
    int x = 16; 
    int y = 10; 
  
    reduceFraction(x, y);
}
}
  
/* This code contributed by PrinciRaj1992 */


Python3
# Python3 program to reduce a fraction x/y 
# to its lowest form
from math import gcd 
  
# Function to reduce a fraction 
# to its lowest form
def reduceFraction(x, y) :
      
    d = gcd(x, y);
  
    x = x // d;
    y = y // d;
  
    print("x =", x, ", y =", y);
  
# Driver Code
if __name__ == "__main__" :
  
    x = 16;
    y = 10;
  
    reduceFraction(x, y);
  
# This code is contributed by Ryuga


C#
// C# program to reduce a fraction x/y 
// to its lowest form 
using System; 
  
class GFG 
{
   
// Function to reduce a fraction to its lowest form 
static void reduceFraction(int x, int y) 
{ 
    int d; 
    d = __gcd(x, y); 
   
    x = x / d; 
    y = y / d; 
   
    Console.WriteLine("x = " + x + ", y = " + y); 
} 
   
static int __gcd(int a, int b) 
{ 
    if (b == 0) 
        return a; 
    return __gcd(b, a % b); 
       
}
   
// Driver Code 
public static void Main(String[] args)
{
    int x = 16; 
    int y = 10; 
   
    reduceFraction(x, y);
}
}
  
// This code has been contributed by 29AjayKumar


PHP


输出

x = 8, y = 5