An Armstrong number is a number, where the sum of the powers (digit raised to the count of digits) of each digit of the number equals that number. An integer of n digits can be called an Armstrong number if it satisfies the following condition,
abcd...=an+bn+cn+dn+...
where,
A three-digit number can call an Armstrong number if the sum of the cubes of each digit of the number equals that number. For example, take 153, the digits of 153 are 1,5 & 3. The cubes of each digit are as shown below.
Then the sum of the cubes: 1 + 125 + 27 = 153 so it is an Armstrong number.
In this R program, we accept the user's input, a 3-digit number into num by providing an appropriate message to the user using 'prompt
' inside the readLine()
function. Using a while loop
extract each digit and find the sum of the cubes of each digit. After calculation check the sum is equal to the given number itself; if yes then it is an Amstrong number, otherwise, it is not.
STEP 1: Prompting appropriate messages to the user take user input using readline()
into variable num
STEP 2: Initialize sum=0 and move temp = num
STEP 3: Find the sum of the cube of each digit using while loop
with condition temp > 0
STEP 4: Compare the sum with num, if they are equal then print
the number is an Armstrong number otherwise not.
To understand more about the concept, we assure you our blog The basics of Armstrong numbers will help you very much.
We recommend you to go through this related R program also, a number with n digits is Armstrong or not
num = as.integer(readline(prompt="Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while(temp > 0) {
digit = temp %% 10
sum = sum + (digit ^ 3)
temp = floor(temp / 10)
}
if(num == sum) {
print(paste(num, "is an Armstrong number"))
} else {
print(paste(num, "is not an Armstrong number"))
}
Enter a number: 230 [1] "230 is not an Armstrong number" Enter a number: 370 [1] "370 is an Armstrong number"