Guest User

Untitled

a guest
Oct 15th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. ##################################################################
  2. # Brute force method for finding all the prime numbers between
  3. # nMin and nMax
  4. ##################################################################
  5.  
  6. findPrimes <- function(nMin, nMax) {
  7. # make sure min number is larger than 1, and break if true
  8. if (nMin == 1)
  9. stop("\n\n **** Error: Please ensure nMin is larger than 1 (nMin > 1) ****")
  10.  
  11. # make sure nMax isnt too large!
  12. if (nMax > 1e+08)
  13. stop("\n\n **** Error: nMax too large!!, try nMax < 1e8 ****")
  14.  
  15. # create a test range going from nMin to nMax
  16. test.range = c(nMin:nMax)
  17.  
  18. # create iterator it
  19. it <- 2
  20.  
  21. # iterate through test.range looking for multiples of smaller numbers
  22. while (it < nMax) {
  23. if (it %in% test.range) {
  24. #test whether 'it' is in test.range
  25. test.range <- sort(c(it, test.range[test.range%%it != 0])) #if yes, then remove multiples amd ensure 'it' is added to updated list. this ensures small primes remain in list.
  26. } else {
  27. test.range <- test.range[test.range%%it != 0] #if no, then remove large multiples
  28. }
  29. it <- it + 1
  30. }
  31. test.range
  32. }
  33.  
  34.  
  35.  
  36. #######################################
  37. # Usage
  38. #######################################
  39.  
  40. findPrimes(11,87)
Add Comment
Please, Sign In to add comment