<?xml version="1.0"?>

<!-- Loop Example: Computing Prime Numbers / Sieve of Erastothenes
     GPL (c) Oliver Becker, 2000-07-01
     obecker@informatik.hu-berlin.de
-->

<xslt:transform version="1.0"
                xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
                xmlns:loop="http://informatik.hu-berlin.de/loop">

<xslt:output method="text" />

<xslt:param name="bound" select="1000" />

<xslt:template match="/">
   <xslt:text />Prime Numbers (2 - <xslt:value-of select="$bound" />
   <xslt:text>) / Sieve of Erastothenes&#xA;</xslt:text>

   <xslt:variable name="array">
      <loop:for name="i" from="1" to="$bound">-</loop:for>
   </xslt:variable>
   <loop:for name="count" from="2" to="$bound">
      <xslt:variable name="is-prime" 
                     select="substring($array,$count,1)='-'" />
      <xslt:if test="$is-prime">
         <xslt:value-of select="$count" />, <xslt:text />
      </xslt:if>
      <xslt:variable name="marked">
         <xslt:choose>
            <xslt:when test="$is-prime and 
                             $count * $count &lt;= $bound">
               <loop:for name="i" 
                         from="$count" to="$bound" step="$count">
                  <xslt:variable name="new-array"
                        select="concat(
                                concat(substring($array,1,$i - 1),'*'),
                                substring($array,$i + 1))" />
                  <xslt:if test="$i + $count &gt; $bound">
                     <xslt:value-of select="$new-array" />
                  </xslt:if>
                  <loop:update name="array" select="$new-array" />
               </loop:for>
            </xslt:when>
            <xslt:otherwise>
               <xslt:value-of select="$array" />
            </xslt:otherwise>
         </xslt:choose>
      </xslt:variable>
      <loop:update name="array" select="$marked" />
   </loop:for>

   <xslt:text>&#xA;</xslt:text>
</xslt:template>

</xslt:transform>
