 # python - armstrong between given interval

Need solution for python code!

How can we find the armstrong numbers in given interval.

I have written the code successfuly to identify the number, but could not be able to get the desired output.

``````lower = int(input())
upper = int(input())

for num in range(lower,upper + 1):
sum = 0
temp = num
armstrong = ""
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
armstrong = armstrong + (str(num) + " ")
print(armstrong)
``````

Case - 1
Input :
150
200

Expected out put :
153
This case was successful.

Case - 2:
Input :
1
3

Expected output :
1 2 3
Could not get the proper output for this one!

According to the definition, an Armstrong (Narcissistic) number is basically a number that is the sum of its own digits each raised to the power of the number of digits.
Therefore, change :
`sum += digit ** 3`
to
`sum += digit ** len(str(num))`

1 Like

Hey brother, thanks a lot for responding.

iam getting output in three different lines.
output iam getting :
1
2
3

output i need
1 2 3

output should be in single line, can you help me here?

Use `print(armstrong, end = " ")` instead.

1 Like

Thanks a lot brother,

There is one more issue. If there is no armstrong number in the given range, then the output should be “-1”.

Sorry that I didn’t mentioned this above.

You can use a boolean variable, say `flag` which is initialised as `False` at the beginning. When you print an Armstrong number, set that flag to `True`. Now, in the end, if `flag` is still `False`, it indicates you haven’t printed any Armstrong number. So we print `-1` in that case.

``````lower = int(input())
upper = int(input())
flag = False
for num in range(lower, upper + 1):
...
...
while temp > 0:
...
...
if num == sum:
flag = True
...
...
if not flag:
print(-1)
``````
1 Like

Rewrite the above as:

``````    while temp > 0:
digit = temp % 10
sum += digit ** len(str(num))
temp //= 10
if num == sum: # Check the Indentation here
print(num, end = " ")
``````
1 Like

It helped brother,

Thanks a lot