This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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

in Engine by (41 points)

1 Answer

0 votes

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.

by (14 points)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.