Here we are explaining how to write an R program to find the factors of a given number. Give the required number as an argument and display its factors using the function print_factors(). Using for loop iterate from 1 to the given number. Print the value if it is perfectly dividing our given value. Finally, we get the list of factors.
Given below are the steps which are used in the R program to find factors of a number. In this R program, we give the number directly to the function print_factors(). Using for loop iterate through the values from 1 to given number. Check each number that perfectly divides the given number if yes print that number.
# Define a function.
print_factors <- function(k) {
print(paste("The factors of given number",k,"are:"))
for(i in 1:k) {
if((k %% i) == 0) {
print(i)
}
}
}
# Call the function.
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
# Call the function.
print_factors(84)
## [1] "The factors of given number 84 are:"
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 6
## [1] 7
## [1] 12
## [1] 14
## [1] 21
## [1] 28
## [1] 42
## [1] 84