w3resource

R Programming: Find the Factors of a given number


Write a R program to find the factors of a given number.

Sample Solution :

R Programming Code :

# Define a function to print the factors of a given number
print_factors = function(n) {
  
  # Print a message indicating the factors of the given number
  print(paste("The factors of", n, "are:"))
  
  # Loop from 1 to the given number to find factors
  for(i in 1:n) {
    
    # Check if the current number is a factor of n
    if((n %% i) == 0) {
      
      # Print the factor
      print(i)
    }
  }
}

# Call the function to print factors of 4
print_factors(4)

# Call the function to print factors of 7
print_factors(7)

# Call the function to print factors of 12
print_factors(12)

Output:

[1] "The factors of 4 are:"
[1] 1
[1] 2
[1] 4
[1] "The factors of 7 are:"
[1] 1
[1] 7
[1] "The factors of 12 are:"
[1] 1
[1] 2
[1] 3
[1] 4
[1] 6
[1] 12                         

Explanation:

  • Define Function: print_factors is defined as a function that takes one argument n.
  • Print Statement: The function first prints a message indicating that it will display the factors of n.
  • Loop Through Numbers: A for loop iterates from 1 to n.
  • Check Divisibility: Within the loop, it checks if i is a factor of n by using the modulus operator (%%).
  • Print Factor: If i is a factor (i.e., n %% i equals 0), i is printed.
  • Function Calls: The function print_factors is then called with the values 4, 7, and 12, printing their respective factors.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to extract first 10 english letter in lower case and last 10 letters in upper case and extract letters between 22nd to 24th letters in upper case.
Next: Write a R program to find the maximum and the minimum  value of a given vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.