Home > Software design >  Checking for prime number in R, why this option using 'break' doesn't work
Checking for prime number in R, why this option using 'break' doesn't work

Time:10-30

starting to get familiar with R. can't get why this simple chunk doesn't work

want to do it particularly using 'break'

prime.check <- function(num) {
  for (del in 2:(num-1)) {
    if (num %% del == 0) {
      break
    }
    print(paste(num, 'is not prime'))
  }
}

CodePudding user response:

Your function is going to print every time in the loop, which is not really what is desired: you should be finishing the loop and then determining what to print. I suggest assuming it is a prime and then if you break, then know that it is not a prime.

See

prime.check <- function(num) {
  isprime <- TRUE
  for (del in 2:(num-1)) {
    if (num %% del == 0) {
      isprime <- FALSE
      break
    }
  }
  isnot <- if (isprime) "is" else "is not"
  print(paste(num, isnot, "prime"))
  invisible(isprime)
}

prime.check(7)
# [1] "7 is prime"
prime.check(6)
# [1] "6 is not prime"

FYI, the invisible(isprime) allows you to use this function elsewhere, such as if (prime.check(8)) { do_something(); }, whereas with the print alone you couldn't do that. Completely ancillary from your original request.

CodePudding user response:

The condition inside the for loop checks if num is divisible by del without a reminder, e.g. it is not prime. In addition, use return instead of break to finalize a function.

prime.check <- function(num) {
  if(num == 2) return("prime")
  for (del in 2:(num-1)) {
    if (num %% del == 0) {
      return("not prime")
    }
  }
  return("prime")
}

prime.check(2)
#> [1] "prime"
prime.check(3)
#> [1] "prime"
prime.check(4)
#> [1] "not prime"
prime.check(9)
#> [1] "not prime"
prime.check(10)
#> [1] "not prime"

CodePudding user response:

Here is another option with no loop:

prime.check <- function(x){
  if(sum(x %% 1:x  == 0) == 2) return(paste(x, 'is prime'))
  return(paste(x, 'is not prime'))
}

prime.check(2)
#> [1] "2 is prime"
prime.check(3)
#> [1] "3 is prime"
prime.check(4)
#> [1] "4 is not prime"
prime.check(9)
#> [1] "9 is not prime"
prime.check(10)
#> [1] "10 is not prime"

CodePudding user response:

You can do this without a loop:

prime.check <- function(num) {
    if (num==2) return("2 is prime")
    if (all(num %% seq(2, num/2) > 0)) {
        return(paste(num, "is prime"))
        } else return(paste(num, "is not prime"))
}
  • Related