Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (50.2k points)

The below code is written on RStudio, and this code will remove every element in the vector which is a multiple of x for each x in the vector.

When I run the function, the loop only works for the first element in the vector, ie, 2, and it doesn't verify the remaining elements such as 3,4,5,6. How can I correct it?

my_function <- function(n){

X <- 2:n

i <- 2

 for (x in X){

   while (x*i <= n){

     a <- match(x*i,X)

     X <- X[-(a)]

     i <- i+1





1 Answer

0 votes
by (108k points)

You can have this function:

my_function <- function(n){

   X <- seq_len(n)

   X[n %% X != 0]



#[1] 4 5


#[1]  5  7  8  9 10 11

If you are a beginner and want to know more about R then do refer to the R programming tutorial.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94.1k users

Browse Categories