I am trying to write a short script that can print out all prime numbers up to 100 and if the number is less than 2 then return "false". I am a bit stuck with the logic that I have.. still new to programming so the codes may not make sense to some of you (don't be tooo harsh) and not sure how to turn ideas into codes..but this is what I have for now!
prime_numbers <- function(x){
pnums <- vector()
for (i in 2:x) {
if (i >= 2) {
pnums = c(pnums,i)
return (pnums)
if (i %% 2==0) {
return(FALSE)
}
}
}
}
prime_numbers(100)
CodePudding user response:
Your logic isn't quite right here. Perhaps something like this?
prime_numbers <- function(x)
{
if(x < 2) return(FALSE)
result <- vector()
for(i in 2:x) if(!any(i %% result == 0)) result <- c(result, i)
return(result)
}
This seems to give the desired behaviour:
prime_numbers(100)
#> [1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
prime_numbers(2)
#> [1] 2
prime_numbers(1000)
#> [1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61
#> [19] 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151
#> [37] 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251
#> [55] 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359
#> [73] 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463
#> [91] 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593
#> [109] 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701
#> [127] 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827
#> [145] 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953
#> [163] 967 971 977 983 991 997
This isn't a very efficient algorithm, since computation time grows exponentially, taking about 150 microseconds to find all the primes under 100, 3 milliseconds for all primes under 1,000, and 200 milliseconds for all primes under 10,000. Still, the logic is hopefully easy to follow.
Created on 2021-10-19 by the reprex package (v2.0.0)