R Program - Find all factors of a Number
Objective: Write a R program to find all distinct factors (divisors) of a given natural number. The divisors of few numbers are given below:
Number: 10 Divisors: 1 2 5 10 Number: 15 Divisors: 1 3 5 15 Number: 100 Divisors: 1 2 4 5 10 20 25 50 100
Method 1: Using iteration
One of the basic approach is to iterate from 1 to n and in each iteration check whether the number divides n. If it divides then print it.
#function to print all divisors of a number printDivisors <- function(n) { cat("Divisors of", n ,"are: ") #creating vector to store all divisors divisors <- c() for (i in c(1:n)) { if(n%%i == 0) { #storing all divisors divisors <- c(divisors, i) } } cat(divisors, "\n") } printDivisors(10) printDivisors(50) printDivisors(100)
The above code will give the following output:
Divisors of 10 are: 1 2 5 10 Divisors of 50 are: 1 2 5 10 25 50 Divisors of 100 are: 1 2 4 5 10 20 25 50 100
Method 2: Optimized Code
Instead of checking the divisibility of the given number from 1 to n, it is checked till square root of n. For a factor larger than square root of n, there must the a smaller factor which is already checked in the range of 1 to square root of n.
#function to print all divisors of a number printDivisors <- function(n) { cat("Divisors of", n ,"are: ") #creating vector to store all divisors divisors <- c() #loop from 1 to sqrt(n) for (i in c(1:sqrt(n))) { if(n%%i == 0) { #storing all divisors if(n%/%i == i) { divisors <- c(divisors, i) } else { divisors <- c(divisors, i, n%/%i) } } } cat(divisors, "\n") } printDivisors(10) printDivisors(50) printDivisors(100)
The above code will give the following output:
Divisors of 10 are: 1 10 2 5 Divisors of 50 are: 1 50 2 25 5 10 Divisors of 100 are: 1 100 2 50 4 25 5 20 10
Method 3: Optimized Code with sorted result
In the previous method, results are produced in a irregular fashion (printed in pairs - small number and large number). The result can be sorted by using R sort() function. Consider the example below:
#function to print all divisors of a number printDivisors <- function(n) { cat("Divisors of", n ,"are: ") #creating vector to store all divisors divisors <- c() #loop from 1 to sqrt(n) for (i in c(1:sqrt(n))) { if(n%%i == 0) { #storing all divisors if(n%/%i == i) { divisors <- c(divisors, i) } else { divisors <- c(divisors, i, n%/%i) } } } divisors <- sort(divisors) cat(divisors, "\n") } printDivisors(10) printDivisors(50) printDivisors(100)
The above code will give the following output:
Divisors of 10 are: 1 2 5 10 Divisors of 50 are: 1 2 5 10 25 50 Divisors of 100 are: 1 2 4 5 10 20 25 50 100