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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { n <- as.integer(readline(prompt = "Enter a number :")) i = 1 s = 0 while (i < n) { if (n %% i == 0) { s = s + i } i = i + 1 } if (s == n) { print(paste("The number is perfect :", n)) } else{ print(paste("The number is not perfect :", n)) } } |
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:
1 2 3 4 | Enter a number :6 [1] "The number is perfect : 6" |