首页 > 编程知识 正文

如何在两个给定整数之间找到阿姆斯特朗数

时间:2023-11-26 13:13:30 阅读:309458 作者:IPEQ

一个整数被称为 n 阶的阿姆斯特朗数。当它的每一个数字被分开,立方,并加在一起,那么它将导致一个和这个数相同的和,(即 pqrs...= pn+qn+rn+sn+...).

如果有一个三位数的阿姆斯特朗数,则每个数中的立方体总数等于该数本身。

示例:


371 = 3 * 3 * 3 + 7 * 7 * 7 + 1 * 1 * 1  
    = 27 + 343 + 1
    = 371        
Therefore, 371 is an Armstrong number.

在本教程中,我们将学习如何使用 Python 语言在两个给定的整数之间找到阿姆斯特朗数。

例如:


Input: Two Integer Numbers: 1000 10000
Output: Armstrong Numbers Between Two Given Integers: 1634 8208 9474
Explanation: For the Output numbers: 1000 and 10000 are given two integers. (interval)
  1634 = 1 * 1 * 1 * 1 + 6 * 6 * 6 * 6 + 3 * 3 * 3 * 3 + 4 * 4 * 4 *4  
      = 1 + 1296 + 81 + 256
      = 1634
  8208 = 8 * 8 * 8 * 8 + 2 * 2 * 2 * 2 + 0 * 0 * 0 * 0 + 8 * 8 * 8 * 8  
      = 4096 + 16 + 0 + 4096
      = 8206
  9474 = 9 * 9 * 9 * 9 + 4 * 4 * 4 *4 + 7 * 7 * 7 * 7 + 4 * 4 * 4 *4
      = 6561 + 256 + 2401 + 256 
      = 9474

我们下面使用的方法很简单。我们查看该范围内的所有数字。对于每个数字,我们首先确定其中的位数。使当前数字的小数位数总和为数字“n”。然后我们计算每个数字的第 n 次方的和。如果总和大于“K”,那么我们记录结果。

代码:


# First we will import required module:
import math
lower1 = int(input("Please enter the lower range of the integer: "))
upper1 = int(input("Please enter the upper range of the integer: "))
print("The Armstrong Numbers Between Two Given Integers:")
for num_1 in range(lower1, upper1 + 1):

   # Now, we will set the order of number
   order1 = len(str(num_1))

   # here, we are initializing sum
   sum = 0

   temp1 = num_1
   while temp1 > 0:
       digit1 = temp1 % 10
       sum += digit1 ** order1
       temp1 //= 10

   if num_1 == sum:

       print(num_1)

输出:

Please enter the lower range of the integer:  1000
Please enter the upper range of the integer:  10000
The Armstrong Numbers Between Two Given Integers:
1634
8208
9474

结论

在本教程中,我们讨论了如何使用 Python 编程打印两个给定整数之间的阿姆斯特朗数。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。