Armstrong Number
|
|
The function isArmstrong
first converts the integer n
into a string to find the number of digits (k
). Then, it initializes a variable sum_of_powers
to store the sum of the k
-th powers of each digit.
The function then goes through each digit in the number. For each digit, it converts the digit back into an integer, calculates the k
-th power of the digit, and adds it to sum_of_powers
.
Finally, the function checks if sum_of_powers
is equal to n
. If they are equal, the number is an Armstrong number, and the function returns True
. Otherwise, it returns False
.
excerpt: This covers the basic building blocks such as Modulo Operator, Sum Accumulator and Reducing Input by Integer Division.
Armstrong number is a number where the sum of cubes of digits of number is equal to the number itself.
Example:
370 = 3*3*3 + 7*7*7 + 0*0*0
= 27 + 343 + 0
= 370
Task Breakdown
- Extract every digit in the given number
- Cube every digit
- Add it to running sum
First task can be implemented as follows:
First Task
|
|
Iteration 1
We can modify the program to calculate the sum:
|
|
The final iteration now checks for Armstrong number:
Iteration 2
|
|
The input is not mutated, copy variable is used to extract digits.
Building Blocks
- Modulo Operator
- Sum Accumulator
- Reducing Input by Integer Division