0

Trying to create a for loop in which you input a number and the function tells you whether or not the number is prime or not. I used two examples being n1 <- 100 and n2 <- 101.

Here is my code below:

    n1 <- 100
    n2 <-101

    answer = TRUE
    for(i in n1){
    if (n1 %% (i-1) == 0){
    prime1=FALSE
    }else {
    prime1=TRUE
    }
    }

    prime1

    answer = TRUE
    for (i in n2){
    if (n2 %% (i-1) == 0){
    prime2=FALSE
    }else {
    prime2=TRUE
    }
    }

    prime2

The problem is that the function will generate the same output for both depending on one difference in the code.

In the first "if" statement, both functions will generate output TRUE if I put in the line (i-1). However, if I instead change the line of code to "n1 %% i == 0" as opposed to "n1 %% (i-1) == 0", both functions generate the output FALSE.

Any pointers? Thanks!

Mochi_Rat
  • 1
  • 1
  • 1
    Your loops iterate over just one index. Do you want to use `1:n1` instead of simply `n1`? – Martin Gal Dec 06 '22 at 19:45
  • Lots of prime number tests here: https://stackoverflow.com/questions/19767408/prime-number-function-in-r. If you need to test multiple numbers it may be better to use a sieve of Eratosthenes approach: https://stackoverflow.com/questions/3789968/generate-a-list-of-primes-up-to-a-certain-number – MrFlick Dec 06 '22 at 19:48
  • Yeah that was the original thread that I found but none of the solutions use a for loop. – Mochi_Rat Dec 06 '22 at 20:05

1 Answers1

0

Here's a simple prime checker using a for loop.

With n1 <- 100 :

for(i in seq(2, ceiling(sqrt(n1)))) {
  if(n1 %% i == 0){
    print(FALSE)
    break
  }
  if(i == ceiling(sqrt(n1)))
    print(TRUE)
}

#> [1] FALSE

With n2 <- 101

for(i in seq(2, ceiling(sqrt(n2)))) {
  if(n2 %% i == 0){
    print(FALSE)
    break
  }
  if(i == ceiling(sqrt(n2)))
    print(TRUE)
}

#> [1] TRUE
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87