##----------------------------------------------------------------------
## sieve7.18.R
##
## Naive implementation of Sieve of Eratosthenes search for primes.
##
## 18/04/2020
##----------------------------------------------------------------------
sink('sieve7.18.out')

rm(list=objects())

find.primes <- function(kfac, kmax=100L) {
    vbool <- rep(1L, kmax)            ## ends up as 1s for primes
    for( jj in 1:length(kfac) ) {
        for( ii in 2:(kmax %/% kfac[jj]) ) {
            kk <- ii*kfac[jj]
            vbool[kk] <- 0L       ## kkth is not a prime
        }
    }
    kPRIMES <- which(vbool == 1)      
    kPRIMES <- kPRIMES[kPRIMES > 1]
    list(vbool=vbool, kprimes=kPRIMES)
}

kFAC <- c(2, 3, 5, 7)  ## start with known primes between 0 and 10

for( jloop in 1:7 ) {
    ## next two lines are to avoid running out of memory on Windows
    if( exists('list1') ) { rm(list1) }
    gc()  
    if( jloop==1 ) {
        kMAX <- 100L
    } else {
        kMAX <- as.integer(10*kMAX)
    }
    print(system.time(
        list1 <- find.primes(kfac=kFAC, kmax=kMAX)
    ))
    print(kMAX)
    print(length(list1$vbool))      ## storage length of vector of booleans
    print(length(list1$kprimes))    ## the number of primes found
    kFAC <- list1$kprimes
}

sink()