Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
R Program to Find the Factors of a Number
In this example, you'll learn to find all factors of an number (entered by the user) using for loop and if statement.
Example: Find factors of a number
print_factors <- function(x) {
print(paste("The factors of",x,"are:"))
for(i in 1:x) {
if((x %% i) == 0) {
print(i)
}
}
}
Output
> print_factors(120) [1] "The factors of 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
In this program we take a number and display its factors using the function print_factors().
In the function, we use a for loop to iterate from 1 to that number and only print it if, it perfectly divides our number. Here, print_factors() is a user-defined function.