w3resource

Check Armstrong number with While loop in R

R Programming: Control Structure Exercise-10 with Solution

Write a R program to check if a given number is Armstrong number using a while loop.

Sample Solution :

R Programming Code :

# Define a function to check if a given number is an Armstrong number
is_armstrong <- function(number) {
    # Store the original number in a temporary variable
    original_number <- number
    
    # Initialize variables for storing the sum of cubes of digits and the number of digits
    sum_of_cubes <- 0
    num_digits <- 0
    
    # Count the number of digits in the given number
    while (number > 0) {
        num_digits <- num_digits + 1
        number <- number %/% 10
    }
    
    # Reset the number to its original value
    number <- original_number
    
    # Calculate the sum of cubes of digits
    while (number > 0) {
        digit <- number %% 10
        sum_of_cubes <- sum_of_cubes + digit^num_digits
        number <- number %/% 10
    }
    
    # Check if the sum of cubes of digits is equal to the original number
    if (sum_of_cubes == original_number) {
        return(TRUE)  # The number is an Armstrong number
    } else {
        return(FALSE)  # The number is not an Armstrong number
    }
}

# Test the function with an example input
number <- 9474  # Example number to check if it's an Armstrong number
is_armstrong_number <- is_armstrong(number)

# Print the result
if (is_armstrong_number) {
    cat(number, "is an Armstrong number.\n")
} else {
    cat(number, "is not an Armstrong number.\n")
}

Output:

9474 is an Armstrong number.               

Explatnaion:

In the exercise above,

  • The "is_armstrong()" function checks if a given number is an Armstrong number.
  • It first stores the original number in a temporary variable.
  • Then, it calculates the number of digits in the given number by repeatedly dividing it by 10 until it becomes 0, incrementing a counter variable ('num_digits') with each iteration.
  • Next, it resets the number to its original value and calculates the sum of cubes of digits by extracting each digit from the number and raising it to the power of the number of digits ('num_digits').
  • Finally, it checks if the calculated sum of cubes of digits is equal to the original number. If they are equal, the function returns 'TRUE', indicating that the number is an Armstrong number; otherwise, it returns 'FALSE'.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Sum of Cubes calculation with For loop in R.
Next: Find GCD with Recursion in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.