Home > Software design >  R stops working and arrows disappearing with prime check function
R stops working and arrows disappearing with prime check function

Time:10-27

prime <- function(number){
    if (number!=2){
        for (num in 1:number){
            while ((number%%num)==0){
                counter <- 0
                counter <- counter 1
                
            }
        }
        return((counter-2)==0)
    }else{
        FALSE
    }
}

My function was designed for prime test, prime numbers only divided by itself and 1. So I've looped all the numbers from 1 to n(number itself) and counted the number of the 0 remainder divisions. Result must be 2 (n/n and n/1 remainders are 0) so (counter-2)==0 returns TRUE if the number is the prime number. Only exception is 2. But my code doesn't working also stops the RStudio. Code line arrows disappearing, R stops return any value.
What is wrong with this code?

CodePudding user response:

I don't think you need a loop for this. Also, I'm not sure what you mean by the line arrow disappears, but this code works for me:

is.prime <- function(x){
  if( x == 2) return(TRUE)
  sum(x %% 1:x  == 0) == 2
}

is.prime(2)
#> [1] TRUE

is.prime(10)
#> [1] FALSE

is.prime(11)
#> [1] TRUE

CodePudding user response:

There are at least 3 problems with your code:

  1. You are arbitrarily defining 2 as being non-prime. It is prime and there is no reason to treat it as a special case.
  2. You are constantly resetting counter to 0. It should be initialized just once outside of the for loop
  3. Your while loop is an infinite loop. If (number%%num)==0 then nothing in the body of the loop will make that false. This causes the loop to be an infinite loop, which is why RStudio hangs when you run your code. The fix is to change this loop into something which is not a loop at all -- it is really an if statement that you need.

Fixing these problems (plus a couple of other tweaks) leads to the following code:

prime <- function(number) {
  counter <- 0
  for (num in 1:number) {
    if ((number %% num) == 0) {
      counter <- counter   1
    }
  }
  counter == 2
}

This succeeds in correctly testing for primes. It is an extremely inefficient test, but making it more efficient would be the topic of another question.

  • Related