简体   繁体   中英

Python - Triangular and Narcissist numbers functions

Code needs functions that returns whether a number is Triangular and if it's Narcissist. Main function:

def main():

playing = True
while playing == True:

    num_input = input('Give me a number from 1 to 10000.  Type -1 to exit. ')

    try:
        num = int(num_input)

        if (num == -1):
            playing = False
            continue

        if (num <= 0 or num > 10000):
            continue

        factors = getFactors(num)
        print("The factors of", num, "are", factors)

 if isTriangular(num):
            print(str(num) + ' is triangular')
 if isNarcissistic(num):
            print(str(num) + ' is narcissistic')

Little I was able to achieve:

def isTriangular(x):
if x = (x + (x +1)) / 2 => 0:
    return isTriangular(x)


def isNarcissistic(x):

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM