Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

The main question is that we need to print the first Armstrong number in the range of 1042000 to 702648265 and terminate the loop as soon as we meet the first Armstrong number. Use while loop

This is my code :

upper = 702648265

lowers=1042000

for num in range (lower, upper + 1):

    o= len (str(num))

    sum = 0

    temp = num

    while temp > 0:

        x = temp % 10

        sum += x ** o

        temp //= 10

    if num == sum:

        print(num)

        break

Output:

1741725

I got 1741725 answers in my output. but when I check Armstrong's number mathematically it's the wrong answer. 

1 Answer

0 votes
by (108k points)

Your answer is right. Your code still needs to be improved a bit.

Your code:

upper = 702648265

lowers=1042000

for num in range (lower, upper + 1):

Corrected code:

upper = 702648265

lowers=1042000

for num in range (lowers, upper + 1): #it should be lowered instead of lower

Here o is 7. So you have to calculate to the power of 7 on each number

1 ^ 7 + 7 ^ 7 + 4 ^ 7 + 1 ^ 7 + 7 ^ 7 + 2 ^ 7 + 5 ^ 7

= 1 + 823543 + 16384 + 1 + 823543 + 128 + 78125

= 1741725

So the answer is correct. 

If you want to learn python then do check out the below python tutorial video for better understanding:

Related questions

0 votes
1 answer
asked May 15, 2021 in Java by sheela_singh (9.5k points)
0 votes
4 answers
0 votes
1 answer

Browse Categories

...