A triangular number N is an integer for which there is another integer x where x(x+1)/2 = N.
So you need to reverse this relation in and figure out the value of x from N, then check if x is an integer.
Using the quadratic root function (-b +√(b^2-4ac))/2a
on the canonical version of the relation x^2/2 + x/2 - N = 0
,
we get x = (√(8N+1)-1)/2
so you can implement isTriangular by computing x from N and checking if it is an integer:
def isTriangular(N):
x = ((8*N+1)**0.5-1)/2
return int(x) == x
Alternatively, you could go through values of x one by one until you reach or exceed N. This has an exponential progression so it shouldn't take too much time (and you don't have to worry about rounding issues with square roots)
def isTriangular(N):
x = n = 1
while n < N:
x += 1
n = x*(x+1)//2
return n == N
For the narcissist number, you need to break N into its individual digits. This is easiest by using a string version of the number and transforming each character back into a numeric value. Then compute the sum of digits raised to the power of number-of-digits and compare it to N.
def isNarcissist(N):
digits = [int(c) for c in str(N)]
return N == sum(d**len(digits) for d in digits)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…