Skip to content

Instantly share code, notes, and snippets.

@jedifran
Created May 30, 2012 02:32
Show Gist options
  • Select an option

  • Save jedifran/2833109 to your computer and use it in GitHub Desktop.

Select an option

Save jedifran/2833109 to your computer and use it in GitHub Desktop.

Revisions

  1. jedifran created this gist May 30, 2012.
    41 changes: 41 additions & 0 deletions findPrimes.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    ##################################################################
    # Brute force method for finding all the prime numbers between
    # nMin and nMax
    ##################################################################

    findPrimes <- function(nMin, nMax) {
    # make sure min number is larger than 1, and break if true
    if (nMin == 1)
    stop("\n\n **** Error: Please ensure nMin is larger than 1 (nMin > 1) ****")

    # make sure nMax isnt too large!
    if (nMax > 1e+08)
    stop("\n\n **** Error: nMax too large!!, try nMax < 1e8 ****")

    # create a test range going from nMin to nMax
    test.range = c(nMin:nMax)

    # create iterator it
    it <- 2

    # iterate through test.range looking for multiples of smaller numbers
    while (it < nMax) {
    if (it %in% test.range) {
    #test whether 'it' is in test.range
    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.
    } else {
    test.range <- test.range[test.range%%it != 0] #if no, then remove large multiples
    }
    it <- it + 1
    }
    test.range
    }



    #######################################
    # Usage
    #######################################

    findPrimes(11,87)