Python Egyptian fractions calculation

Asked 2 years ago, Updated 2 years ago, 31 views

Hello, I'm making an Egyptian fountain with Python. Given a fraction, the largest molecule is expressed as a fraction with one, for example

egypt(4,5) 4/5 = 1/2 + 1/4 + 1/20 [2, 4, 20]

egypt(2,11) 2/11 = 1/6 + 1/66 [6, 66]

egypt(761, 1000) 761/1000 = 1/2 + 1/4 + 1/91 + 1/91000 [2, 4, 91, 91000]

It's expressed like this. For your information, you should use a greedy algorithm and not use division and fractional functions. All calculations have to be integers, and the key is to calculate (n/d) - (1/c), so what's the way to calculate without using division and fractions?

python python3

2022-09-21 10:20

2 Answers

When you divide natural numbers, you don't always divide them, but in this case, Python uses approximate values instead of exact values, so division may not solve the problem.

I tried to make the code myself, but I don't think it's going to be easy. I'll give you a rough idea, so try to implement it yourself

I think that's a good idea, but instead of using division when you do three, you have to separate both numbers and find the denominator and the numerator, just like we solve the math problem ourselves

After subtracting, you need to divide x and y.

The i-values and the last y-values obtained over and over again will be the values that this function should return.

I think you can get the desired value in this form, but try to implement the details yourself Haha


2022-09-21 10:20

def egypt(numerator, denominator):
    nr = numerator
    dr = denominator
    c = 2
    fraclist = []
    if nr == 1 and dr !=0:
        print("{}/{}").format(nr,dr)
    while nr != 1:
        if nr < dr and nr != 0 or dr != 0:            
            if (c*nr - dr) > (dr * c):
                nr = c*nr - dr
                dr = c* dr
        c += 1
    fraclist.append("1/{}").format(c)

    print("+".join(fraclist))

I planned it, but it's endless loop. I don't know what's wrongcrying I can't write the code in the reply, so I's reply


2022-09-21 10:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.