Как найти все трехзначные числа армстронга питон

Студворк — интернет-сервис помощи студентам

Число Армстронга. Числом Армстронга считается натуральное число, сумма цифр которого, возведенных в N-ную степень (N – количество цифр в числе) равна самому числу.
Например, 153 = 1^3 + 5^3 + 3^3.

Можно использовать только циклы и условный оператор, без списков, массивов и.т.д. Я написал вот так:

Python
1
2
3
for i in range(100,1000):
    if i%10**3 + i//10%10**3 + i//100**3 == i:
        print(i)

Но вообще ничего не выводит. Помогите!
P.S у меня от 100 до 1000, потому что я сначала хотел на этом отрезке попробовать.

Михаил



Профи

(754),
закрыт



3 года назад

Натуральное число называется числом Армстронга, если сумма цифр числа, возведенных в N-ную степень (где N – количество цифр в числе) равна самому числу. Например, 153 = 13 + 53 + 33. Найдите все трёхзначные Армстронга. На языке Python (Питон) пожалуйста!

Лучший ответ

Black Afgano

Просветленный

(21949)


3 года назад

for x in range(100, 1000):
~~~~a = 0
~~~~for d in str(x):
~~~~~~~~a+= int(d) ** 3
~~~~if a == x:
~~~~~~~~print(x)

МихаилПрофи (754)

3 года назад

Спасибо за помощь братан!

Остальные ответы

Дивергент

Высший разум

(1537541)


3 года назад

Всего существует ЧЕТЫРЕ таких числа: 153, 370, 371 и 407

Zerg ZergУченик (145)

1 год назад

Ага, значит 115 132 219 018 763 992 565 095 597 973 971 522 401 не число Армстронга, конечно.

Zerg Zerg, нет

Влад Щиголь

Ученик

(102)


7 месяцев назад

for i in range(153,1000):
a =(i // 100 % 10) **3
b =(i // 10 % 10) **3
c =(i % 10) **3
if a+b+c == i:
print(i)

Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.

abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... 

Example:

Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153

Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9

Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723

Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

Python

def power(x, y):

    if y == 0:

        return 1

    if y % 2 == 0:

        return power(x, y // 2) * power(x, y // 2)

    return x * power(x, y // 2) * power(x, y // 2)

def order(x):

    n = 0

    while (x != 0):

        n = n + 1

        x = x // 10

    return n

def isArmstrong(x):

    n = order(x)

    temp = x

    sum1 = 0

    while (temp != 0):

        r = temp % 10

        sum1 = sum1 + power(r, n)

        temp = temp // 10

    return (sum1 == x)

x = 153

print(isArmstrong(x))

x = 1253

print(isArmstrong(x))

Time complexity: O((logn)2)

Auxiliary Space: O(1)

Method: A positive integer is called an Armstrong number if an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because
   153 = 1*1*1 + 5*5*5 + 3*3*3
    The while loop iterates like first, it checks if the number is not equal to zero or not. if it is not equal to zero then enter into the loop and find the reminder of number ex: 153%10 gives reminder 3. In the next step add the cube of a number to the sum1(3*3*3). Then the step gives the quotient of the number (153//10=15). this loop will continue till the given number is equal to zero.
 

Python3

n = 153 

s =

b = len(str(n))

sum1 = 0

while n != 0:

    r = n % 10

    sum1 = sum1+(r**b)

    n = n//10

if s == sum1:

    print("The given number", s, "is armstrong number")

else:

    print("The given number", s, "is not armstrong number")

Output

The given number 153 is armstrong number

Please refer complete article on Program for Armstrong Numbers for more details!

Time complexity: O(logn)

Auxiliary Space: O(1)

Approach#3: Using string manipulation

This approach involves converting the input number into a string and iterating through each digit in the string. For each digit, we raise it to the power of the number of digits in the input number, and sum up the results. If the final sum equals the input number, it is an Armstrong number.

Algorithm

1. Convert the input number into a string using str(num).
2. Find the length of the string using len(num_str) and store it in n.
3. Initialize a variable sum to zero.
4. Iterate through each digit in the string using a for loop, and convert each digit back to an integer using int(digit).
5. Raise each digit to the power of n using int(digit)**n, and add the result to sum.
6. After the loop is complete, check whether sum is equal to num.
7. If sum is equal to num, return True (the input number is an Armstrong number).
8. If sum is not equal to num, return False (the input number is not an Armstrong number).

Python3

def is_armstrong(num):

    num_str = str(num)

    n = len(num_str)

    sum = 0

    for digit in num_str:

        sum += int(digit)**n

    if sum == num:

        return True

    else:

        return False

num=153

print(is_armstrong(num))

Time complexity: O(n), wheer n is length of number
Auxiliary Space: O(1)

Method: Digit by digit sum approach to check for Armstrong number

  1. Find the number of digits in the given number.
  2. Initialize a variable sum to zero.
  3. Extract each digit from the given number and raise it to the power of the number of digits and add it to the sum.
  4. If the sum is equal to the given number, then it is an Armstrong number, else it is not. #include <iostream>
     

Python3

import math

def isArmstrong(num):

    n = num

    numDigits = 0

    sum = 0

    while n > 0:

        n //= 10

        numDigits += 1

    n = num

    while n > 0:

        digit = n % 10

        sum += math.pow(digit, numDigits)

        n //= 10

    if sum == num:

        return True

    return False

num1 = 1634

if isArmstrong(num1):

    print(num1, "is an Armstrong number.")

else:

    print(num1, "is not an Armstrong number.")

num2 = 120

if isArmstrong(num2):

    print(num2, "is an Armstrong number.")

else:

    print(num2, "is not an Armstrong number.")

Output

1634 is an Armstrong number.
120 is not an Armstrong number.

Time Complexity: O(log n), where n is the given number.
Auxiliary Space: O(1)

Last Updated :
11 Apr, 2023

Like Article

Save Article

I’m going to focus on the performance aspect, as I believe other parts already have good answers. While the program may be simple and performant, it is still fun to go in and micro-optimize a little. In general I would recommend against it.

Here is your code put into a function to make it clear what changes in the future. I’ve made the function return the numbers since that was easier for me to work with. I don’t have anything new that I would suggest changing.

def armstrong(lower, upper):
    armstrong_numbers = []
    for num in range(lower, upper + 1):
        order = len(str(num))
        sum = 0

        temp = num
        while temp > 0:
            digit = temp % 10
            sum += digit ** order
            temp //= 10

        if num == sum:
            armstrong_numbers.append(num)

    return armstrong_numbers

Precompute

A google search says another name for these numbers are narcissistic numbers and that there are only a finite number of them (88 to be exact). We could make a list of the numbers, loop over the list and return the numbers between lower and upper. This only works if someone else has done the work and generated all the numbers already.

Precompute a little

The above point could be useful though, the first 9 armstrong numbers are the numbers 1 through 9. Let’s “precompute” as many of those as we need. We should really add a check to make sure lower <= upper, but alas…

def armstrong(lower, upper):
    cutoff = min(10, upper + 1)
    armstrong_numbers = list(range(lower, cutoff))
    if lower < 10:
        lower = 10

    for num in range(lower, upper + 1):
        order = len(str(num))
        sum = 0

        temp = num
        while temp > 0:
            digit = temp % 10
            sum += digit ** order
            temp //= 10

        if num == sum:
            armstrong_numbers.append(num)

    return armstrong_numbers

Optimize the powers

Another good point that showed up when googling armstrong numbers is that no number bigger than 1060 can be an armstrong number. This means we can work out every possible answer for digitorder ahead of time and reuse it each loop. This should be useful as I think computing arbitrary powers is not as fast as looking up the answer in a table.

As plainly as I can state it, there are only 10 digits, and order is at most 60, so we can make a table 10 * 60 big that stores all the answers to digitorder and use that instead.

def armstrong(lower, upper):
    cutoff = min(10, upper + 1)
    armstrong_numbers = list(range(lower, cutoff))
    if lower < 10:
        lower = 10

    powers_table = [[d ** n for d in range(10)] for n in range(60)]

    for num in range(lower, upper + 1):
        order = len(str(num))
        row = powers_table[order]  # We only care about one row of the table at a time.
        sum = 0

        temp = num
        while temp > 0:
            digit = temp % 10
            sum += row[digit]
            temp //= 10

        if num == sum:
            armstrong_numbers.append(num)

    return armstrong_numbers

Check less numbers

The last idea that I found online (see section 5) is to skip numbers with certain prefixes. We can guarantee a number will never work if it the sum of all of its digits except the last one is odd.

The reason for this is as follows. Raising a number to a power won’t change its parity. In other words if a number x is even, xn is also even. If x is odd xn is also odd. The sum of the digits raised to a power n will have the same parity as the sum of the digits. For example if we have the 3 digit number 18X. The sum of it’s digits cubed is 1**3 (odd) + 83 (even) + X3 which is the same as 1 (odd) + 8 (even) + X.

Assume the sum of all the digits of an armstrong number excluding the last digit is odd then we have either

(A**n + B**n + C**n + ...W**n) + X**n == odd + X**n == odd if X is even or
(A**n + B**n + C**n + ...W**n) + X**n == odd + X**n == even if X is odd

But if the last digit (X) is even, the sum has to be even it to which it isn’t.
If the last digit is odd, the sum has to be odd, but it isn’t. Either way, we get a contradiction, so our assumption must be wrong.

The code is a bit messy, but it gives the idea. It agrees with the other snippets above for the query (1, 100000)

def armstrong3(lower, upper): 
    cutoff = min(10, upper + 1) 
    armstrong_numbers = list(range(lower, cutoff)) 
    if lower < 10: 
        lower = 10 

    powers_table = [[d ** n for d in range(10)] for n in range(60)] 

    start, end = lower // 10, upper // 10 
    for leading_digits in range(start, end + 1): 
        if sum(c in "13579" for c in str(leading_digits)) % 2 == 1: 
            # Skip numbers with an odd sum parity 
            continue 

        order = len(str(leading_digits)) + 1  # We will add a last digit later 
        row = powers_table[order]  # We only care about one row of the table at a time. 
        sum = 0 

        temp = leading_digits 
        while temp > 0: 
            digit = temp % 10 
            sum += row[digit] 
            temp //= 10 

        for last_digit in range(10): 
            final_total = sum + row[last_digit] 
            if 10 * leading_digits + last_digit == final_total and final_total <= upper: 
                armstrong_numbers.append(num) 

    return armstrong_numbers

Micro-benchmarked locally I get the following

%timeit armstrong(1, 100000)
143 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit armstrong2(1, 100000)
69.4 ms ± 2.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit armstrong3(1, 100000)
14.9 ms ± 31.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So the extra tuning was worth it.

Other work

I didn’t get around to implementing the ideas at this github project. The code is in java and run with N < 10 at the smallest (above you can see my benchmarks were only for N < 5), so I don’t think the performance is anywhere near as good as that code. It would be the next place to go if you are interested in pushing things further.

I looked at using divmod instead of modding and dividing by 10. The performance was worse for me, so I chose not to use it.

%timeit armstrong(1, 100000)
143 ms ± 104 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit armstrong_divmod(1, 100000)
173 ms ± 5.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Hello there! Today let us learn something Interesting, Armstrong Number. We would be understanding what the number is and then implement a program to check if a number is an Armstrong Number or not.

What is an Armstrong Number?

A number of n digits is an Armstrong number, if sum of each digit raised to the power of the no of digits is equal to the original number.

Armstrong Number definition is : abcd…(n-digits) = a^n + b^n + c^n + d^n + . . . . . and so on.

Examples of Armstrong Number

Example 1 : 153

Total number of digits = 3

Calculation (digit – wise ) = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

The calculation done is directly equal to the original number. Hence the number is an Armstrong number.

Example 2 : 548834

Total number of digits = 6

Calculation (digit – wise) = 5^6 + 4^6 +8^6 + 8^6 + 3^6 + 4^6 = 15625 + 4096 + 262144 + 262144 + 729 + 4096 = 548834

The calculations done is directly equal to the original number. Hence the number is an Armstrong Number.

Algorithm to check Armstrong Number

To check if a number is an Armstrong number, one needs to follow the following steps

  1. Count the number of digits in the number.
  2. Each digit is accessed one after another with the help of mod and division operations
  3. Each digit is raised to the power of the number of digits and the result is stored in a separate variable
  4. Steps 2 and 3 are repeated until the digits exhaust.
  5. Check the result calculated with the original number
    • If It matches: Armstrong Number
    • Otherwise: Not an Armstrong Number

PseudoCode for Armstrong Number

The code below shows the pseudo code to check if a number is an Armstrong Number:

READ n
CALCULATE NO OF DIGITS n_digit
MAKE A COPY OF n
result=0

CHECK DIGIT BY DIGIT:
  WHILE n!=0
     GET CURRENT DIGIT : digit = n % 10
     UPDATE RESULT : result = result + digit^(n_digit)
     TRIM THE LAST DIGIT : n = n / 10
  ENDWHILE

CHECK FOR ARMSTRONG NUMBER:
   IF result==COPY OF n
      PRINT "ARMSTRONG NUMBER"
   ELSE
      PRINT "NOT AN ARMSTRONG NUMBER"

Implementing Armstrong Number Checking in Python

Now that we know about what Armstrong Number is and the steps to implement that, let’s implement the Armstrong checking line by line.

1. Create the intital variables

We first take an input n and then calculate the length of the input. We also store a copy of the input so that no matter how much we change the original number, we have the copy to check Armstrong’s number later. We also initialized the result as 0.

The code for the same is shown below:

n = input()
n_digit = len(n)
n=int(n)
copy_n=n
result = 0

2. Traversing through the number and Updating Result

To access each digit we take the modulus of the number ( mod 10 ) to extract the last digit of the number. The next step involves updating the result as the sum of the previous result and the digit raised to the power of the number of digits.

The last and final step we take is divide the number by 10 to drop the last digit from the number. The same process is repeated until there are no more digits are left in the number.

The code for the same is shown below:

while(n!=0):
    digit = n%10
    result=result+pow(digit,n_digit)
    n=int(n/10)

3. Checking if the number is an Armstrong Number or not

The final step is to check the copy of the number we created earlier with the result calculated to finally tell if the number is an Armstrong number or not. The code for the same is shown below:

if(result==copy_n):
    print("Armstrong Number!")
else:
    print("Not an Armstrong Number!")

Output Samples for the code

For now I tested the program for four inputs. The outputs for all four is shown below:

Number 1: 153

Number 2: 121

121
Not an Armstrong Number!

Number 3: 548834

Number 4: 9468632

9468632
Not an Armstrong Number!

Conclusion

Congratulations! You have successfully learned about Armstrong Number and implemented the same!

But don’t stop here! Keep Reading and Learning!

Добавить комментарий