pythonalgorithmdivide-and-conquer

How to print a fraction in latex form?


I have a fraction and I want to print the latex form of it. The fraction is like this for n == 3: enter image description here

How can I print the latex for this fraction using divide and conquer: 1+\frac{2+\frac{4}{5}}{3+\frac{6}{7}}

And for n == 4 the fraction is: enter image description here

And the result is: 1+\frac{2+\frac{4+\frac{8}{9}}{5+\frac{10}{11}}}{3+\frac{6+\frac{12}{13}}{7+\frac{14}{15}}}


Solution

  • I found the solution myself. I've tried to solve the problem by using divide and conquer. My solution has two parameters, start and step. Start is the value that is printed at the first step. and step is the value that shows the number of fractions. If step = 1, then I print just the value of start. Otherwise for each step the numerator of the fraction is 2start and for denominator the value is 2start+1. Here is the code of my solution.

    def generate_fraction(start : int, step : int):
      result = ""
      if step == 1:
        result = str(start)
      else:
        result = str(start) + '+\\frac{'+ generate_fraction(2*start, step-1) + '}{' + generate_fraction(2*start + 1, step-1) + '}'
      return result
    
    # Main Program ...
    step = int(input())
    start = 1
    print(generate_fraction(start, step))