Open In App

R Program to check Armstrong Number

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An Armstrong number (also known as a narcissistic number or pluperfect digital invariant) is a number that is equal to the sum of its own digits each raised to the power of the number of digits in the number. For example, a 3-digit Armstrong number would be equal to the sum of the cubes of its digits.

In R Programming Language there are some steps required to create a program for Armstrong number.

To check if a number is an Armstrong number, we need to:

  • Determine the number of digits in the given number.
  • Calculate the sum of each digit raised to the power of the number of digits.
  • Compare the sum with the original number to check if it is an Armstrong number.

To check for an Armstrong number in R, follow these steps:

a. Take the input number from the user or use a predefined number.

b. Find the number of digits in the number.

c. Calculate the sum of each digit raised to the power of the number of digits.

d. Compare the sum with the original number to check if it is an Armstrong number.

e. Display the result.

Below is an example of an R program to check if a number is an Armstrong number

R




# Function to check for an Armstrong number
is_armstrong_number <- function(number) {
  num <- number
  num_of_digits <- nchar(num)
  sum_of_digits <- 0
 
  while (num > 0) {
    digit <- num %% 10
    sum_of_digits <- sum_of_digits + digit^num_of_digits
    num <- num %/% 10
  }
 
  return(sum_of_digits == number)
}
 
# Example usage
number_to_check <- 153
if (is_armstrong_number(number_to_check)) {
  cat(number_to_check, "is an Armstrong number.")
} else {
  cat(number_to_check, "is not an Armstrong number.")
}


Output:

153 is an Armstrong number.

R program to check Armstrong number for user-defined value

R




is_armstrong_number <- function(num) {
  num_of_digits <- nchar(num)
  original_number <- num
  sum_of_digits <- 0
   
  while (num > 0) {
    digit <- num %% 10
    sum_of_digits <- sum_of_digits + digit^num_of_digits
    num <- num %/% 10
  }
   
  return(sum_of_digits == original_number)
}
 
# User input
user_input <- as.numeric(readline("Enter a number to check if it's
                           an Armstrong number:"))
 
if (!is.na(user_input)) {
  if (is_armstrong_number(user_input)) {
    cat(user_input, "is an Armstrong number.")
  } else {
    cat(user_input, "is not an Armstrong number.")
  }
} else {
  cat("Invalid input. Please enter a valid number.")
}


Output:

155 is not an Armstrong number.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads