Looping for infinitely decreasing input

I need to loop a code for an indefinite number of times until my "if" code becomes true. Each time the code must be for one less value of the input. How can this be done?

This is the code I've been working with:

prime <- function(x){
    a <- seq_len(x)
    b <- length(a[ x%%a == 0])
    if(b>2){
        c <- seq_len(x-1)
        d <- length(c[( x-1)%%c == 0])
        if(d>2){
            "true"
        }
    }  
}

Is there an easier way of having the (x-1) in objects c and d?

The aim is to determine whether the input is a prime number or not. If the argument is a prime number then the function should return the next (larger) prime number. If not, the function should return the closest prime number below the input.

Welcome to the community!

Is implementing this in an easy way your question? But I think your implementation is not correct? It indicates 16 as prime, which is not. See below:

prime <- function(x) {
  a <- seq_len(x)
  b <- length(a[(x %% a) == 0])
  if (b > 2) {
    c <- seq_len(x - 1)
    d <- length(c[(x - 1) %% c == 0])
    if (d > 2) {
      "true"
    }
  }
}

prime(x = 16)
#> [1] "true"

Created on 2019-03-20 by the reprex package (v0.2.1)

I've just no idea why have you done this. If there are only two factors, then they have to be unity and the number itself. So, you can conclude about prime or not prime only from b.

Again, I can't follow why do you expect this will be the case. Your code doesn't check either for either case.

This question seems to be a assignment problem. Please familiarise yourself with the existing policy:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.