当前分类:300例题>>正文

Python示例:检查数字是否是 diarium 数字

来源:互联网   更新时间:2023年6月18日  

Python 示例

编写一个 Python示例来检查一个数字是不是一个 diarium 数字,或者是否使用 while 循环。如果一个给定数的数字加到其各自位置的幂的和等于实际数,它就是一个 diarium 数字。例如,175 = 11 + 72 + 53 = 1 + 49 + 125 = 175。

在这个 Python示例中,我们将数字分成单个数字,并求出总和。接下来,if 语句检查总和是否等于实际数字。如果是真的,这是一个灾难性的数字。

Number = int(input("Enter the Number to Check Disarium Number = "))
length = len(str(Number))

Temp = Number
Sum = 0
rem = 0

while Temp > 0:
    rem = Temp % 10
    Sum = Sum + int(rem**length)
    Temp = Temp // 10
    length = length - 1

print("The Sum of the Digits = %d" %Sum)

if Sum == Number:
    print("\n%d is a Disarium Number." %Number)
else:
    print("%d is Not a Disarium Number." %Number)

在这个 Python 例子中,我们使用了 digitsCount 和 digitsSum 来检查这个数字是否是一个异数。

import math

def digitsCount(Number):
    length = 0
    while Number != 0:
        length = length + 1
        Number = Number // 10
    return length

def digitsSum(Number, length):
    Sum = 0
    rem = 0

    while Number > 0:
        rem = Number % 10
        Sum = Sum + math.pow(rem, length)
        Number = Number // 10
        length = length - 1
    return Sum

Number = int(input("Enter the Number to Check Disarium Number = "))
length = digitsCount(Number)
Sum = digitsSum(Number, length)

print("The Sum of the Digits     = %d" %Sum)

if Sum == Number:
    print("%d is a Disarium Number." %Number)
else:
    print("%d is Not a Disarium Number." %Number)
Enter the Number to Check Disarium Number = 175
The Sum of the Digits     = 175
175 is a Disarium Number.

Enter the Number to Check Disarium Number = 24
The Sum of the Digits     = 18
24 is Not a Disarium Number.

Python示例检查一个数字是不是一个 diarium 数字或者没有使用递归。

import math

length = 0
Sum = 0

def digitsCount(Number):
    global length
    if Number > 0:
        length = length + 1
        digitsCount(Number // 10)
    return length

def digitsSum(Number, length):
    global Sum
    if Number > 0:
        rem = Number % 10
        Sum = Sum + math.pow(rem, length)
        digitsSum(Number // 10, length = length - 1)
    return Sum

Number = int(input("Enter the Number to Check Disarium Number = "))
length = digitsCount(Number)
Sum = digitsSum(Number, length)

print("The Sum of the Digits     = %d" %Sum)

if Sum == Number:
    print("\n%d is a Disarium Number." %Number)
else:
    print("%d is Not a Disarium Number." %Number)
Enter the Number to Check Disarium Number = 98
The Sum of the Digits     = 73
98 is Not a Disarium Number.

Enter the Number to Check Disarium Number = 135
The Sum of the Digits     = 135

135 is a Disarium Number.
本文固定链接:https://6yhj.com/leku-p-4316.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 百度爬虫