# Arup Guha
# 10/20/2020
# Solves a Quadratic with real roots.
# With our own two functions sqrt, pow

# Edited in lecture so that a redundant call to mysqrt isn't made!

# Pre-conditions: base is a floating pt number, exp is an integer.
def mypow(base, exp):

    # If exp is negative, flip it and get the positive answer and then do 1/over.
    if exp < 0:
        return 1.0/mypow(base, -exp)

    # Exponent is positive.
    ans = 1
    for i in range(exp):
        ans = ans*base

    return ans

# Pre-condition: x is a positive real value.
# Post-condition: Returns the square root of x.
def mysqrt(x):

    # Get safe low and high bounds.
    low = min(1, x)
    high = max(1, x)

    # Improve our answer 100 times.
    for i in range(100):

        # Guess halfway between our bounds.
        mid = (low+high)/2

        # Update either our lowest or highest possible answer.
        if mid*mid > x:
            high = mid
        else:
            low = mid

    # This should be pretty close to the square root.
    return low

# Our program
def main():

    # Read in the coefficients to the quadratic.
    a = float(input("Please enter a from your quadratic equation.\n"))
    b = float(input("Please enter b from your quadratic equation.\n"))
    c = float(input("Please enter c from your quadratic equation.\n"))

    # Calculate the discriminant.
    discriminant = mypow(b, 2) - 4*a*c

    # Real roots.
    if discriminant >= 0:

        # Only change is adding term so that we don't redundantly call mysqrt!
        term = mysqrt(discriminant)
        root1 = (-b + term)/(2*a)
        root2 = (-b - term)/(2*a)

        # Print out the roots.
        print("The roots of your quadratic are",root1,"and",root2)

    # Complex roots.
    else:

        # Get the real and imaginary parts.
        real = -b/(2*a)
        img = mysqrt(-discriminant)/(2*a)

        print("One root is ", real," + ", img, "i.", sep="")
        print("The other root is ", real," - ", img, "i.", sep="")

# Run it!
main()
        

