Project Euler #42: Coded triangle numbers

  • + 0 comments

    Umm... Solution for Python 3 I think So!!!

    import math
    
    a, b, c = 1, 1, -2
    
    def solve_quadratic(N):
        D = int(math.sqrt(b**2 - 4 * a * c * N))
        n1 = (-b - D) // (2 * a)
        n2 = (-b + D) // (2 * a)
        
        if n1 > 0 and N == n1 * (n1 + 1) // 2:
            return n1
        elif n2 > 0 and N == n2 * (n2 + 1) // 2:
            return n2
        else:
            return -1
    
    def main():
        num_cases = int(input().strip())
        for _ in range(num_cases):
            N = int(input().strip())
            result = solve_quadratic(N)
            print(result)
    
    if __name__ == "__main__":
        main()