R Lang

R Program to check a number is a perfect number or not1 min read

In this program, You will learn how to check a number is a perfect number or not in R.

Example: How to check a number is a perfect number or not in R




A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding itself. For example, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.

The code first reads in a value for n from the user and stores it as an integer. It then initializes two variables, i and s, to 1 and 0, respectively.

The code then enters a while loop which continues to execute as long as i is less than n. Inside the loop, the code uses the modulo operator (%%) to check if i is a divisor of n. If it is, the code adds i to s. The loop then increments i by 1 and the process is repeated.

After the while loop has finished executing, the code uses an if statement to check if the sum of the divisors of n (stored in s) is equal to n. If it is, the code prints a message saying that n is a perfect number. If s is not equal to n, the code prints a message saying that n is not a perfect number.

The output of this program would depend on the value of n that is entered by the user. Here is an example of what the output might look like:

Leave a Comment