Factors of a number 'n' are the integers that can able to divide the original number 'n' into equal parts without any remainder. for example, let us consider the integer 8 and let us check the factors of 8. they are 1, 2, and 4, because they can divide the integer 8 without any remainder.
In this R program, we give the number directly to the function print_factors(). Inside the function, using for loop iterate through the values from 1 to a given integer. Check each number if that perfectly divides the given integer using the mod operator, if yes print that number. Finally, we get the list of factors.
STEP 1: Call function print_factors()
STEP 2: Pass the number whose factors need to be found as the function argument.
STEP 3: Using for loop iterate from 1 to the given integer
STEP 4:check if the iterated value perfectly divides our integer
STEP 5:if gives the remainder zero print the value
STEP 6:continue the loop until iteration reaches our number
print_factors <- function(k) {
print(paste("The factors of given number",k,"are:"))
for(i in 1:k) {
if((k %% i) == 0) {
print(i)
}
}
}
print_factors(120)
[1] "The factors of given number 120 are:" [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 8 [1] 10 [1] 12 [1] 15 [1] 20 [1] 24 [1] 30 [1] 40 [1] 60 [1] 120