Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R how do I find whether an integer is divisible by a number?

Tags:

loops

for-loop

r

Sorry for the inexperience, I'm a beginning coder in R For example: If I were to make a FOR loop by chance and I have a collection of integers 1 to 100 (1:100), what would be the proper format to ensure that would print the numbers that are divisible by another number. In this case, 5 being the number divisible. I hear that using modulo would help in this instance %%

This is what I think I should have.

For (x in 1:100) {
  x%%5 == y
}
print(y)
like image 615
John Dorksy Avatar asked Apr 12 '17 02:04

John Dorksy


People also ask

Which operator can be used to test the divisibility of a number?

The operator %% is called a divisibility operator. It tells if the left operand can be integer divided by the right operand without a remainder.

How can one tell if an integer is divisible?

An integer is divisible by three if the sum of the digits is divisible by three. For example, to determine if 5838232 is divisible by three, we calculate 5+8+3+8+2+3+2=31.

How do you find out if the number that the user entered is divisible by the other in python?

In Python, the remainder operator (“%”) is used to check the divisibility of a number with 5. If the number%5 == 0, then it will be divisible.

How do you check if a number is divisible by any number?

A number is divisible by another number if it can be divided equally by that number; that is, if it yields a whole number when divided by that number. For example, 6 is divisible by 3 (we say "3 divides 6") because 6/3 = 2, and 2 is a whole number.


3 Answers

for (x in 1:100) { 
  if (x%%5 == 0) {
    print(x)
  }
}
like image 99
Andrew Lavers Avatar answered Sep 21 '22 06:09

Andrew Lavers


The modulo operator %% is used to check for divisibility. Used in the expression x %% y, it will return 0 if y is divisible by x.

In order to make your code work, you should include an if statement to evaluate to TRUE or FALSE and replace the y with 0 inside the curly braces as mentioned above:

for (x in 1:100) { 
  if (x%%5 == 0) {
    print(x)
  }
}

For a more concise way to check for divisibility consider:

for (x in 1:100) { 
  if (!(x%%5)){
    print(x)
  }
}

Where !(x %% 5) will return TRUE for 0 and FALSE for non-zero numbers.

like image 38
iamericfletcher Avatar answered Sep 21 '22 06:09

iamericfletcher


How's this?

x <- 1:100
div_5 <- function(x) x[x %% 5 == 0]
div_5(x)
like image 43
Jonathan Hill Avatar answered Sep 22 '22 06:09

Jonathan Hill