w3resource

Check Perfect number using While loop in R

R Programming: Control Structure Exercise-15 with Solution

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

From Wikipedia -
In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. The next perfect number is 28, since 1 + 2 + 4 + 7 + 14 = 28.

Sample Solution :

R Programming Code :

# Define a function to check if a given number is a perfect number using a while loop
is_perfect_number <- function(number) {
    # Initialize variables
    sum_of_divisors <- 0
    divisor <- 1
    
    # Find proper divisors and sum them
    while (divisor < number) {
        if (number %% divisor == 0) {
            sum_of_divisors <- sum_of_divisors + divisor
        }
        divisor <- divisor + 1
    }
    
    # Check if the number is a perfect number
    if (sum_of_divisors == number) {
        return(TRUE)  # Number is a perfect number
    } else {
        return(FALSE)  # Number is not a perfect number
    }
}

# Test the function with an example input
number <- 28  # Example number to check if it's a perfect number
is_perfect <- is_perfect_number(number)

# Print the result
if (is_perfect) {
    cat(number, "is a perfect number.\n")
} else {
    cat(number, "is not a perfect number.\n")
}

Output:

28 is a perfect number.           

Explatnaion:

In the exercise above,

  • The "is_perfect_number()" function takes a positive integer 'number' as input and checks if it's a "perfect" number.
  • It initializes 'sum_of_divisors' to 0 and 'divisor' to 1.
  • It iterates through each divisor less than 'number' using a while loop.
  • For each divisor that evenly divides 'number', it adds it to 'sum_of_divisors'.
  • After finding all the proper divisors and summing them, it checks if 'sum_of_divisors' is equal to 'number'.
  • If they are equal, the function returns 'TRUE', indicating that the number is a "perfect" number. Otherwise, it returns 'FALSE'.

R Programming Code Editor:



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

Previous: Calculate Sum of Odd elements in Array using For loop in R.
Next: Reverse number using While loop in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-15.php