R Program to find the factors of a number

How to find the factors of a number

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.

How factors of a number check are implemented in R Program

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.

ALGORITHM

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 given number

STEP 4:check if the iterated value perfectly divides our number

STEP 5:if gives remainder zero print the value

STEP 6:continue the loop until iteration reaches our number

 

R Source Code

                                          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)
                                      

OUTPUT

[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