R - Prime Numbers

This R code will generate tables containing the first 2 million numbers, whether that number is prime (divisible only itself and 1) or not, its lowest divisor (or 0 for primes).  The final two statements result in displaying the percent of non-prime numbers (92.55%) and prime numbers (7.45%).


num <- 1:2000000
prime <- rep("Prime", 2000000)
divisor <- rep(0, 2000000)
for (x in seq(from=2, to=2000000, by=1)) {
  z <- sqrt(x);
  for (y in 2:z) {
     if (x%%y == 0) {
       prime[x] <- "Non-Prime";
       divisor[x] <- y;
       break;
       }    
    }
}
ptable <- table(prime)
prop.table(ptable)


No comments:

Post a Comment

R - Prime Numbers

This R code will generate tables containing the first 2 million numbers, whether that number is prime (divisible only itself and 1) or not, ...