CFLib.org – Common Function Library Project

createPrimeNumberSequence()

Last updated October 17, 2014

author

Adam Cameron

Version: 1 | Requires: CF10 | Library: CFMLLib

Description:
Each call to the function returned from createPrimeNumberSequence() returns the next prime number.

Return Values:
Returns a function which when called returns the next prime number

Example:

component extends="testbox.system.BaseSpec" {

    function beforeAll(){
        include "udfs/createPrimeNumberSequence.cfm";
    }

    function run(){
        describe("Tests for createPrimeNumberSequence()", function(){
            it("returns primes", function(){
                var primeSequence = createPrimeNumberSequence();
                var primes = [];
                for (var i=1; i++ <= 10;){
                    primes.append(primeSequence());
                }
                expect(
                    primes
                ).toBe([2,3,5,7,11,13,17,19,23,29]);
            });
        });
    }

}

Parameters:

No arguments.

Full UDF Source:

/**
 * Creates a &quot;generator&quot; for returning prime numbers, in sequence
 * 
 * @return Returns a function which when called returns the next prime number 
 * @author Adam Cameron (dac.cfml@gmail.com) 
 * @version 1.1, October 17, 2014 
 */
function createPrimeNumberSequence(){
    var primes = [2]
    var potential = 1

    return function(){
        while (true) {
            potential += 2
            var upperThresholdToCheck = sqr(potential)
            var potentialIsPrime = true
            for (var prime in primes){
                request.called++
                if (potential mod prime == 0) {
                    potentialIsPrime = false
                    break;
                }
                if (prime > upperThresholdToCheck) break;
            }
            if (potentialIsPrime) {
                primes.append(potential)
                return primes[primes.len()-1]
            }
        }
    }
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson