Search⌘ K
AI Features

Discussion: More Simple

Explore how to simplify fractions in C by computing the greatest common divisor through Euclid's algorithm. Learn to implement this method using loops and conditional statements to reduce fractions effectively. Understand the logic behind the algorithm and how to translate it into working C code for fraction simplification.

Run the code

Now, it's time to execute the code and observe the output.

#include <stdio.h>

int main()
{
  int n, d, larger, smaller, diff;
  
  printf("Enter a fraction (nn/nn): ");
  scanf("%d/%d", &n, &d);

  // Check if the denominator is zero
  if (d == 0)
  {
    printf("Error: Denominator cannot be zero.\n");
    return 1;  // Exit the program with an error code
  }

  printf("%d/%d = ", n, d);
  larger = n > d ? n : d;
  smaller = n < d ? n : d;
  diff = larger - smaller;

  while (diff != larger)
  {
    larger = smaller > diff ? smaller : diff;
    smaller = smaller == larger ? diff : smaller;
    diff = larger - smaller;
  }

  if (diff > 1)
    printf("%d/%d\n", n / diff, d / diff);
  else
    printf("%d/%d\n", n, d);

  return 0;
}
C code for the given puzzle

Understanding the output

The code requires that you input two integers in the form of a fraction, such as 21/63. Here's the output:

Enter a fraction (nn/nn):
21/63 = 1/3
Code output

The fraction is reduced—simplified—if it can be. When the fraction can’t be simplified, the original fraction is returned as output.

Explanation

Computers are ...