In this program, You will learn how to check a number is a strong number or not in R.
Example: How to check a number is a strong 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 21 22 23 24 25 26 27 28 | { n <- as.integer(readline(prompt = "Enter a number :")) num = n s = 0 while (n > 0) { r = n %% 10 f = 1 i = 1 while (i <= r) { f = f * i i = i + 1 } s = s + f n = as.integer(n / 10) } if (num == s) print(paste("This is a Strong Number :", num)) else print(paste("This is not a Strong Number :", num)) } |
This code determines whether a given number is a “strong number.” A strong number is a number in which the sum of the factorials of its digits is equal to the number itself. For example, 145 is a strong number because 1! + 4! + 5! = 145. Here is a brief explanation of how the code works:
The program reads in a number and stores it in the variable n
.
The program initializes the variable s
to 0. This variable will be used to store the sum of the factorials of the digits of n
.
The program enters a while
loop that continues as long as n
is greater than 0.
Inside the loop, the program calculates the remainder of n
divided by 10 and stores it in the variable r
. This is done to extract the last digit of n
.
The program initializes the variable f
to 1 and the variable i
to 1. f
will be used to store the factorial of r
, and i
will be used as a counter in a loop to calculate the factorial.
The program enters a while
loop that continues as long as i
is less than or equal to r
.
Inside the loop, the program calculates the factorial of r
by multiplying f
by i
and storing the result back in f
. The program then increments i
by 1.
When the inner loop finishes, the program adds the factorial of r
(stored in f
) to the running total of the factorials of the digits (stored in s
).
The program divides n
by 10 and stores the result back in n
. This is done to remove the last digit of n
.
When the outer loop finishes, the program checks whether the sum of the factorials of the digits (stored in s
) is equal to the original number. If it is, the program prints out a message saying that the number is a strong number. If it is not, the program prints out a message saying that the number is not a strong number.
The program ends.
1 2 3 4 | Enter a number :145 [1] "This is a Strong Number : 145" |