How to make "Fraction Simplifier"

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Konrad

How to make “Fraction Simplifier”? Like

9/18 return 1/2.

14/21 return 2/3

and etc. I didn’t find such a function in the documentation

:bust_in_silhouette: Reply From: Kiroto

There is no function for a Fraction Simplifier on Godot (as far as I am concerned, at least), so you would have to make your own.

You would need to make a function that takes two parameters and return two values (in a data type that can contain two values, like a custom class’s object).

Some of the logic behind the simplifier you will have to figure out yourself (by using examples on other languages, or figuring it out).

One way to do it to divide both the numerator and denominator by prime numbers until at least one them is prime, and then return the result. Here is a definitely not optimized way to do it:

func simplify(n, d): # n for numerator, d for denominator
var somePrimes = [2, 3, 5, 7, 11, 13]
for prime in somePrimes:
	if ((n in somePrimes) or (d in somePrimes)):
		break
	while ((n % prime == 0) and (d % prime == 0)):
		n /= prime
		d /= prime
return Vector2(n, d)

(I used Vector2 for the example because I don’t know what other data structure gdscript has for 2 values, but it is most certainly not optimal)

Using the above function, simplify(14, 21) will yield a Vector2 which’s x is 2 and y is 3

It will check if it can divide by 2, 3, 5 and 7; be able to divide by 7, and then see that the numerator is in the prime numbers list (2 is in fact in the somePrimes list), then stop the loop and return the final values.

Thank you, but i made fraction simplifier by using GCF. It is a best variant
n / gcd(n, d) , d / gcd(n, d)

Konrad | 2021-01-05 21:29