Project Euler #42: Coded triangle numbers

Sort by

recency

|

25 Discussions

|

  • + 0 comments

    python

    from math import sqrt
    for _ in range(int(input())):
        n = int(input())
        s = sqrt(1+8*n)
        if s % 2 == 1:
            print(int((s - 1) // 2))
        else:
            print(-1)
    
  • + 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()
    
  • + 0 comments

    100% python - uses qudratic formula

    import math
    
    a, b, c = 1, 1, -2
    
    for a0 in range(int(input())):
        N = int(input())
        D = int(math.sqrt((b**2 - 4 * a * c * N)))
        n1, n2 = (-b-D)//(2*a), (-b+D)//(2*a)
        #print(N, n1, n2)
        if n1 > 0 and N == n1*(n1+1)//2:
            print(n1)
        elif n2> 0 and N == n2*(n2+1)//2:
            print(n2)
        else:
            print(-1)
    
  • + 0 comments

    Easy solution in Python-3 ''' T = int(input().strip()) for _ in range(T): T_th_n = int(input().strip()) N = ((1 + 8*T_th_n)**0.5-1)/2 if N == int(N): print(int(N)) else: print(-1) '''

    Approach:-

    The code uses a for loop to iterate over a range of T test cases. For each test case, it takes an input T_th_n and calculates N using a mathematical formula. If N is an integer, it prints the integer value of N. Otherwise, it prints -1. The approach seems to be solving a mathematical problem related to finding the value of N.

  • + 0 comments

    Easy solution in Python 3

    t=int(input().strip())
    for _ in range(t):
        tn=int(input().strip())
        a=((1+8*tn)**0.5-1)/2
        if a==int(a):
            print(int(a))
        else:
            print(-1)