Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
966 views
in Technique[技术] by (71.8m points)

logic - 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):
question from:https://stackoverflow.com/questions/65886923/python-triangular-and-narcissist-numbers-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...