Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print numbers divisible by 7

Tags:

r

Is there any function that allows me to check if x is divisible by any number? I need to write a repeat loop with integers ranging from 1:100 and also using if function write all the numbers divisible by 7 from that range. Here is what I got so far:

x <- 1
repeat {
    print(x)
    x = x+1
    if (x > 100) {
        break
    }
}

It only prints first part of what I need.

like image 436
debowak Avatar asked Dec 06 '16 21:12

debowak


1 Answers

You don't have to do all that. Use the modulo operator %% and the beauty of R's vectorization.

which(1:100 %% 7 == 0)
# [1]  7 14 21 28 35 42 49 56 63 70 77 84 91 98

Or if you're playing code golf, make it even shorter ...

which(!1:100 %% 7)
# [1]  7 14 21 28 35 42 49 56 63 70 77 84 91 98
like image 125
Rich Scriven Avatar answered Sep 21 '22 01:09

Rich Scriven