-2

I am solving a problem to Express a number as the sum of consecutive numbers.

So I figured out if we get the roots of quadratic equation form with the formula n((n+1)//2), we can do it o(1) time complexity.

Suppose if we have any number x, if the quadratic equation formed using above formula n((n+1)//2) and the number x contains any valid roots, then it can be as the sum of consecutive numbers else not.

1 Answers1

1

You are looking for the solution to x^2 + x - 2N = 0 where N is the total that the sum of number up to x would produce. If x is an integer then there is a solution. Using the standard quadratic equation solution we come up with:

x = ( -1 + √(1+8N) ) / 2

so you could write your function like this:

def isSumToN(N):
    x = ((8*N+1)**0.5-1)/2
    return int(x) if x%1==0 else False

output:

isSumToN(10)  # 4
isSumToN(101) # False
Alain T.
  • 40,517
  • 4
  • 31
  • 51