Armstrong Numbers in a Range
Armstrong numbers are numbers that are equal to the sum of their own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153 . In this example, we will find all Armstrong numbers within a given range. The program prompts the user to enter a lower and upper bound for the range and then identifies and displays all Armstrong numbers within that range.
Code Breakdown
Algorithm
- Start
- Initialize variables:
i
,n
,d
,lb
,ub
,p
,s
,x
,t
. - Prompt the user to enter the lower bound
lb
and upper boundub
. - Loop through each number
x
fromlb
toub
:- Count Digits:
- Initialize
n
to count the number of digits inx
. - For each digit of
x
, increasen
by 1.
- Initialize
- Calculate Armstrong Sum:
- Initialize
s
to 0. - For each digit of
x
:- Calculate
p
as the digit raised to the power ofn
. - Add
p
tos
.
- Calculate
- Initialize
- Check Armstrong Number:
- If
s
equalsx
, thenx
is an Armstrong number. Printx
.
- If
- Count Digits:
- End
Code Explanation
Example Flowchart
Start
|
V
Input lowerBound, upperBound
|
V
For each number from lowerBound to upperBound
|
V
Calculate the number of digits (numDigits) in current number
|
V
Initialize sum of powered digits (sum = 0)
|
V
+---------------------------+
| For each digit in number: |
| ------------------------- |
| Extract last digit: |
| digit = number % 10 |
| Raise digit to power: |
| power = digit^numDigits |
| Add power to sum: |
| sum += power |
| Remove last digit: |
| number /= 10 |
+---------------------------+
|
V
Is sum of powered digits equal to the original number?
/ \
/ \
Yes No
| |
V V
Print number as Armstrong number Continue to next number
| |
V |
End |
|
V
End