Skip to content

Instantly share code, notes, and snippets.

@twelverobots
Created November 2, 2012 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twelverobots/4001416 to your computer and use it in GitHub Desktop.
Save twelverobots/4001416 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes - Jason
<!--- Create array of all numbers --->
<cfset aNumbers = [] />
<!--- Initialize Array with unmarked, except one --->
<cfset arraySet(aNumbers, 2, 1000, "unmarked") />
<cfset aNumbers[1] = "one" />
<!--- Loop over Array --->
<cfloop from="2" to="#arrayLen(aNumbers)#" index="numIndex">
<!--- If number is already marked, skip it --->
<cfif aNumbers[numIndex] EQ "marked" OR aNumbers[numIndex] EQ "composite">
<cfcontinue />
</cfif>
<!--- If we made it here, number is prime, mark it --->
<cfset aNumbers[numIndex] = "marked" />
<!--- Square the current index to go find multiples of the current prime to mark them --->
<cfset nextNum = numIndex * numIndex />
<!--- Go mark the multiples of the current prime by starting with its square and stepping by the current prime --->
<cfloop from="#nextNum#" to="#arrayLen(aNumbers)#" step="#numIndex#" index="multipleIndex">
<cfset aNumbers[multipleIndex] = "composite" />
</cfloop>
</cfloop>
<style>
td {
margin:0;
padding: 0;
width: 20px;
height: 20px;
padding: 10px;
}
.marked {
background-color: green;
}
.composite {
background-color: red;
}
.one {
background-color: black;
}
</style>
<cfoutput>
<table>
<tr>
<cfloop from="1" to="#arrayLen(aNumbers)#" index="tableIndex">
<td class="#aNumbers[tableIndex]#">#tableIndex#</td>
<cfif tableIndex MOD 10 EQ 0>
</tr>
<tr>
</cfif>
</cfloop>
</tr>
</table>
</cfoutput>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment