R Program to check 3 digit armstrong number

What is an Armstrong number?

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,b,c,d... are the digits
  • n is the count of digits

Here in this R program, we explained how to check whether a 3-digit number is Armstrong or not.

How to check if the given 3-digit number is Armstrong or not?

A three-digit number can call an Armstrong number if the sum of the cubes of each digit of the number equals that number. We need to calculate the sum of the cube of each digit.

For example, take 371, the digits of 371 are 3,7 & 1. The cubes of each digit is as shown below.

33 = 3 x 3 x 3 = 27

73 = 7 x 7 x 7 = 343

13 = 1 x 1 x 1 = 1

Then the sum of the cubes: 27+343+1 = 371  so it is an Armstrong number.

How to solve this Armstrong number logic using R programming?

Given below are the steps used in the R program to read value and check if it is an Armstrong number. 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.

ALGORITHM

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

  • Split a digit of the number with a mod by 10 operation
  • Calculate the sum of cube of that digit with previous
  • Remove that digit and take the rest of the digits by a division with 10 operation

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 

R Source Code

                                          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"))
}
                                      

OUTPUT

Enter a number: 230
[1] "230 is not an Armstrong number"

Enter a number: 370
[1] "370 is an Armstrong number"