<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
		>
<channel>
	<title>Comments on: Monte Carlo Factorization</title>
	<atom:link href="http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/feed/" rel="self" type="application/rss+xml" />
	<link>http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/</link>
	<description>A collection of etudes, updated weekly, for the education and enjoyment of the savvy programmer</description>
	<lastBuildDate>Sat, 11 Feb 2012 09:48:16 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
	<item>
		<title>By: programmingpraxis</title>
		<link>http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/#comment-263</link>
		<dc:creator><![CDATA[programmingpraxis]]></dc:creator>
		<pubDate>Wed, 01 Jul 2009 23:59:25 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.wordpress.com/?p=765#comment-263</guid>
		<description><![CDATA[Instead of eval, you might want to build your own calculator.  See the very first Programming Praxis exercise for an RPN calculator.]]></description>
		<content:encoded><![CDATA[<p>Instead of eval, you might want to build your own calculator.  See the very first Programming Praxis exercise for an RPN calculator.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Mark VandeWettering</title>
		<link>http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/#comment-260</link>
		<dc:creator><![CDATA[Mark VandeWettering]]></dc:creator>
		<pubDate>Wed, 01 Jul 2009 21:48:47 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.wordpress.com/?p=765#comment-260</guid>
		<description><![CDATA[Okay, I fixed a couple of things, and extended the program a tiny bit.   It now is a numeric calculator of sorts.   It&#039;s not industrial strength or anything, but you can basically type any python numeric expression, and it will use eval() (at least with a predefined environment) to evaluate the number.  I&#039;ve also predefined a couple of built in functions.   prime(n) will return an n digit prime.   rsa(n) will return an rsa key which is the combination of two n/2 digit primes.   factor(n) factors n.  I&#039;ve also added code to do some trial division as well, to get rid of small factors, and it collapses multiple occurrences of a factor (instead of printing 128 copies of 2 when factoring 2^128, it outputs &quot;2**128&quot;).  

[sourcecode lang=&quot;python&quot;]
#!/usr/bin/env python

#
# a basic implementation of the Pollard rho factorization
# Written by Mark VandeWettering &lt;markv@pixar.com&gt;
#

import sys
import locale
import random
try:
    import readline
except ImportError, msg:
    print msg
    print &quot;Line editing disabled.&quot;


# an inefficient but straightforward way to find primes...

def primes(n):
    primes = [2]
    for x in range(3, n, 2):
        prime = True
        for p in primes:
            if p * p &gt; n:
                break
            if x % p == 0:
                # it&#039;s composite..
                prime = False
                break
        if prime:
            primes.append(x)
    return primes

class FactorError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def miller_rabin_pass(a, n):
    d = n - 1
    s = 0
    while d % 2 == 0:
        d &gt;&gt;= 1
        s += 1

    a_to_power = pow(a, d, n)
    if a_to_power == 1:
        return True
    for i in xrange(s-1):
        if a_to_power == n - 1:
            return True
        a_to_power = (a_to_power * a_to_power) % n
    return a_to_power == n - 1

def isprime(n):
    for repeat in xrange(20):
        a = 0
        while a == 0:
            a = random.randrange(n)
        if not miller_rabin_pass(a, n):
            return False
    return True

def gcd(a, b):
    while b != 0:
        a, b = b, a%b
    return a

def findfactor(n):
    for c in range(1, 10):
        x = y = random.randint(1, n-1)
        x = (x * x + c) % n
        y = (y * y + c) % n
        y = (y * y + c) % n
        while True:
            t = gcd(n, abs(x-y))
            if t == 1:
                x = (x * x + c) % n
                y = (y * y + c) % n
                y = (y * y + c) % n
            elif t == n:
                break
            else:
                return t
    raise FactorError(&quot;couldn&#039;t find a factor.&quot;)

def factor(n):
    r = []
    for p in primes(10000):
        while n % p == 0:
            r.append(p)
            n = n / p
    if n == 1:
        return r
    while True:
        if isprime(n):
            r.append(n)
            break
        try:
            f = findfactor(n)
            r.append(f)
            n = n / f
        except FactorError, msg:
            r.append(n)
            break
    r.sort()
    return r

# this function would be easier to write recursively, but
# python isn&#039;t good at tail recursion, so in theory, it could
# fail.  Too bad.

def shorten(flist):
    slist = []
    idx = 0
    while flist[idx:] != []:
        hd = flist[idx]
        idx = idx + 1
        exp = 1
        while flist[idx:] != [] and flist[idx] == hd:
            exp = exp + 1
            idx = idx + 1
        if exp &gt; 1:
                slist.append(locale.format(&quot;%d&quot;, hd, True) + &quot;**&quot;+str(exp))
        else:
                slist.append(locale.format(&quot;%d&quot;, hd, True))
    return slist

def factorit(n):
        flist = factor(n)
        print locale.format(&quot;%d&quot;, n, True), &quot;=&quot;
        for f in shorten(flist):
                print &quot;\t%s&quot; % f

locale.setlocale(locale.LC_ALL, &quot;&quot;)

import string

def prime(n):
        &quot;generate an n bit prime&quot;
        while True:
                x = int(&#039;&#039;.join([random.choice(string.digits) for i in range(n)]))
                if isprime(x):
                        return x

def rsapair(n):
        return prime(n//2)*prime(n//2)

env = { &quot;prime&quot; : prime,
        &quot;rsa&quot; : rsapair,
        &quot;factor&quot; : factorit}

while True:
        try:
                num = raw_input(&quot;enter a python numexpr &gt;&gt; &quot;)
                n = eval(num, env)
                if n:
                        print n
        except NameError, msg:
                print &gt;&gt; sys.stderr, msg
        except SyntaxError, msg:
                print &gt;&gt; sys.stderr, msg
        except KeyboardInterrupt, msg:
                print &gt;&gt; sys.stderr, &quot;**Interrupted**&quot;
                continue
        except EOFError, msg:
                print
                break
[/sourcecode]]]></description>
		<content:encoded><![CDATA[<p>Okay, I fixed a couple of things, and extended the program a tiny bit.   It now is a numeric calculator of sorts.   It&#8217;s not industrial strength or anything, but you can basically type any python numeric expression, and it will use eval() (at least with a predefined environment) to evaluate the number.  I&#8217;ve also predefined a couple of built in functions.   prime(n) will return an n digit prime.   rsa(n) will return an rsa key which is the combination of two n/2 digit primes.   factor(n) factors n.  I&#8217;ve also added code to do some trial division as well, to get rid of small factors, and it collapses multiple occurrences of a factor (instead of printing 128 copies of 2 when factoring 2^128, it outputs &#8220;2**128&#8243;).  </p>
<pre class="brush: python;">
#!/usr/bin/env python

#
# a basic implementation of the Pollard rho factorization
# Written by Mark VandeWettering &lt;markv@pixar.com&gt;
#

import sys
import locale
import random
try:
    import readline
except ImportError, msg:
    print msg
    print &quot;Line editing disabled.&quot;

# an inefficient but straightforward way to find primes...

def primes(n):
    primes = [2]
    for x in range(3, n, 2):
        prime = True
        for p in primes:
            if p * p &gt; n:
                break
            if x % p == 0:
                # it's composite..
                prime = False
                break
        if prime:
            primes.append(x)
    return primes

class FactorError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def miller_rabin_pass(a, n):
    d = n - 1
    s = 0
    while d % 2 == 0:
        d &gt;&gt;= 1
        s += 1

    a_to_power = pow(a, d, n)
    if a_to_power == 1:
        return True
    for i in xrange(s-1):
        if a_to_power == n - 1:
            return True
        a_to_power = (a_to_power * a_to_power) % n
    return a_to_power == n - 1

def isprime(n):
    for repeat in xrange(20):
        a = 0
        while a == 0:
            a = random.randrange(n)
        if not miller_rabin_pass(a, n):
            return False
    return True

def gcd(a, b):
    while b != 0:
        a, b = b, a%b
    return a

def findfactor(n):
    for c in range(1, 10):
        x = y = random.randint(1, n-1)
        x = (x * x + c) % n
        y = (y * y + c) % n
        y = (y * y + c) % n
        while True:
            t = gcd(n, abs(x-y))
            if t == 1:
                x = (x * x + c) % n
                y = (y * y + c) % n
                y = (y * y + c) % n
            elif t == n:
                break
            else:
                return t
    raise FactorError(&quot;couldn't find a factor.&quot;)

def factor(n):
    r = []
    for p in primes(10000):
        while n % p == 0:
            r.append(p)
            n = n / p
    if n == 1:
        return r
    while True:
        if isprime(n):
            r.append(n)
            break
        try:
            f = findfactor(n)
            r.append(f)
            n = n / f
        except FactorError, msg:
            r.append(n)
            break
    r.sort()
    return r

# this function would be easier to write recursively, but
# python isn't good at tail recursion, so in theory, it could
# fail.  Too bad.

def shorten(flist):
    slist = []
    idx = 0
    while flist[idx:] != []:
        hd = flist[idx]
        idx = idx + 1
        exp = 1
        while flist[idx:] != [] and flist[idx] == hd:
            exp = exp + 1
            idx = idx + 1
        if exp &gt; 1:
                slist.append(locale.format(&quot;%d&quot;, hd, True) + &quot;**&quot;+str(exp))
        else:
                slist.append(locale.format(&quot;%d&quot;, hd, True))
    return slist

def factorit(n):
        flist = factor(n)
        print locale.format(&quot;%d&quot;, n, True), &quot;=&quot;
        for f in shorten(flist):
                print &quot;\t%s&quot; % f

locale.setlocale(locale.LC_ALL, &quot;&quot;)

import string

def prime(n):
        &quot;generate an n bit prime&quot;
        while True:
                x = int(''.join([random.choice(string.digits) for i in range(n)]))
                if isprime(x):
                        return x

def rsapair(n):
        return prime(n//2)*prime(n//2)

env = { &quot;prime&quot; : prime,
        &quot;rsa&quot; : rsapair,
        &quot;factor&quot; : factorit}

while True:
        try:
                num = raw_input(&quot;enter a python numexpr &gt;&gt; &quot;)
                n = eval(num, env)
                if n:
                        print n
        except NameError, msg:
                print &gt;&gt; sys.stderr, msg
        except SyntaxError, msg:
                print &gt;&gt; sys.stderr, msg
        except KeyboardInterrupt, msg:
                print &gt;&gt; sys.stderr, &quot;**Interrupted**&quot;
                continue
        except EOFError, msg:
                print
                break
</pre>
]]></content:encoded>
	</item>
	<item>
		<title>By: Mark VandeWettering</title>
		<link>http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/#comment-256</link>
		<dc:creator><![CDATA[Mark VandeWettering]]></dc:creator>
		<pubDate>Wed, 01 Jul 2009 16:38:38 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.wordpress.com/?p=765#comment-256</guid>
		<description><![CDATA[Here&#039;s my attempt in Python.   A couple of issues in the code remain.   The factors that it discovers aren&#039;t guaranteed to be prime.   I cribbed the Miller-Rabin test from one of the python code repositories.   And, I don&#039;t really understand exactly how this works.  :-)   Back to the reference books.

[sourcecode lang=&quot;python&quot;]
#!/usr/bin/env python

#
# a basic implementation of the Pollard rho factorization
# Written by Mark VandeWettering &lt;markv@pixar.com&gt;
#

import sys
import locale
import random

class FactorError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def miller_rabin_pass(a, n):
    d = n - 1
    s = 0
    while d % 2 == 0:
        d &gt;&gt;= 1
        s += 1

    a_to_power = pow(a, d, n)
    if a_to_power == 1:
        return True
    for i in xrange(s-1):
        if a_to_power == n - 1:
            return True
        a_to_power = (a_to_power * a_to_power) % n
    return a_to_power == n - 1

def isprime(n):
    for repeat in xrange(20):
        a = 0
        while a == 0:
            a = random.randrange(n)
        if not miller_rabin_pass(a, n):
            return False
    return True

def gcd(a, b):
    while b != 0:
        a, b = b, a%b
    return a

def findfactor(n):
    for c in range(1, 50):
        x = y = random.randint(1, n-1)
        x = (x * x + c) % n
        y = (y * y + c) % n
        y = (y * y + c) % n
        while True:
            t = gcd(n, abs(x-y))
            if t == 1:
                x = (x * x + c) % n
                y = (y * y + c) % n
                y = (y * y + c) % n
            elif t == n:
                break
            else:
                return t
    raise FactorError(&quot;couldn&#039;t find a factor.&quot;)

def factor(n):
    r = []
    while True:
        if isprime(n):
            r.append(n)
            break
        try:
            f = findfactor(n)
            r.append(f)
            n = n / f
        except FactorError, msg:
            r.append(n)
            break
    r.sort()
    return r

def doit(n):
        flist = factor(n)
        print locale.format(&quot;%d&quot;, n, True), &quot;=&quot;
        for f in flist:
                print &quot;\t%s&quot; % locale.format(&quot;%d&quot;, f, True)

locale.setlocale(locale.LC_ALL, &quot;&quot;)

doit(2**98-1)

[/sourcecode]]]></description>
		<content:encoded><![CDATA[<p>Here&#8217;s my attempt in Python.   A couple of issues in the code remain.   The factors that it discovers aren&#8217;t guaranteed to be prime.   I cribbed the Miller-Rabin test from one of the python code repositories.   And, I don&#8217;t really understand exactly how this works.  :-)   Back to the reference books.</p>
<pre class="brush: python;">
#!/usr/bin/env python

#
# a basic implementation of the Pollard rho factorization
# Written by Mark VandeWettering &lt;markv@pixar.com&gt;
#

import sys
import locale
import random

class FactorError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def miller_rabin_pass(a, n):
    d = n - 1
    s = 0
    while d % 2 == 0:
        d &gt;&gt;= 1
        s += 1

    a_to_power = pow(a, d, n)
    if a_to_power == 1:
        return True
    for i in xrange(s-1):
        if a_to_power == n - 1:
            return True
        a_to_power = (a_to_power * a_to_power) % n
    return a_to_power == n - 1

def isprime(n):
    for repeat in xrange(20):
        a = 0
        while a == 0:
            a = random.randrange(n)
        if not miller_rabin_pass(a, n):
            return False
    return True

def gcd(a, b):
    while b != 0:
        a, b = b, a%b
    return a

def findfactor(n):
    for c in range(1, 50):
        x = y = random.randint(1, n-1)
        x = (x * x + c) % n
        y = (y * y + c) % n
        y = (y * y + c) % n
        while True:
            t = gcd(n, abs(x-y))
            if t == 1:
                x = (x * x + c) % n
                y = (y * y + c) % n
                y = (y * y + c) % n
            elif t == n:
                break
            else:
                return t
    raise FactorError(&quot;couldn't find a factor.&quot;)

def factor(n):
    r = []
    while True:
        if isprime(n):
            r.append(n)
            break
        try:
            f = findfactor(n)
            r.append(f)
            n = n / f
        except FactorError, msg:
            r.append(n)
            break
    r.sort()
    return r

def doit(n):
        flist = factor(n)
        print locale.format(&quot;%d&quot;, n, True), &quot;=&quot;
        for f in flist:
                print &quot;\t%s&quot; % locale.format(&quot;%d&quot;, f, True)

locale.setlocale(locale.LC_ALL, &quot;&quot;)

doit(2**98-1)
</pre>
]]></content:encoded>
	</item>
	<item>
		<title>By: Remco Niemeijer</title>
		<link>http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/#comment-182</link>
		<dc:creator><![CDATA[Remco Niemeijer]]></dc:creator>
		<pubDate>Fri, 19 Jun 2009 13:01:12 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.wordpress.com/?p=765#comment-182</guid>
		<description><![CDATA[My Haskell solution (see http://bonsaicode.wordpress.com/2009/06/19/programming-praxis-monte-carlo-factorization/ for a version with comments):

[sourcecode lang=&#039;css&#039;]
import Control.Arrow  
import Data.Bits  
import Data.List  
import System.Random 

isPrime :: Integer -&gt; StdGen -&gt; Bool  
isPrime n g =  
    let (s, d) = (length *** head) . span even $ iterate (`div` 2) (n-1)  
        xs = map (expm n d) . take 50 $ randomRs (2, n - 2) g  
    in all (\x -&gt; elem x [1, n - 1] &#124;&#124;  
                  any (== n-1) (take s $ iterate (expm n 2) x)) xs  
  
expm :: Integer -&gt; Integer -&gt; Integer -&gt; Integer  
expm m e b = foldl&#039; (\r (b&#039;, _) -&gt; mod (r * b&#039;) m) 1 .  
             filter (flip testBit 0 . snd) .  
             zip (iterate (flip mod m . (^ 2)) b) $  
             takeWhile (&gt; 0) $ iterate (`shiftR` 1) e

factor :: Integer -&gt; Integer -&gt; Integer
factor c n = factor&#039; 2 2 1 where
    f x = mod (x * x + c) n
    factor&#039; x y 1 = factor&#039; x&#039; y&#039; (gcd (x&#039; - y&#039;) n) where
                        (x&#039;, y&#039;) = (f x, f $ f y)
    factor&#039; _ _ d = if d == n then factor (c + 1) n else d

factors :: Integer -&gt; StdGen -&gt; [Integer]
factors n g = sort $ fs n where
    fs x &#124; even x      = 2 : fs (div x 2)
         &#124; isPrime x g = [x]
         &#124; otherwise   = f : fs (div x f) where f = factor 1 x

main :: IO ()
main = print . factors (2^98 - 1) =&lt;&lt; getStdGen
[/sourcecode]]]></description>
		<content:encoded><![CDATA[<p>My Haskell solution (see <a href="http://bonsaicode.wordpress.com/2009/06/19/programming-praxis-monte-carlo-factorization/" rel="nofollow">http://bonsaicode.wordpress.com/2009/06/19/programming-praxis-monte-carlo-factorization/</a> for a version with comments):</p>
<pre class="brush: css;">
import Control.Arrow
import Data.Bits
import Data.List
import System.Random 

isPrime :: Integer -&gt; StdGen -&gt; Bool
isPrime n g =
    let (s, d) = (length *** head) . span even $ iterate (`div` 2) (n-1)
        xs = map (expm n d) . take 50 $ randomRs (2, n - 2) g
    in all (\x -&gt; elem x [1, n - 1] ||
                  any (== n-1) (take s $ iterate (expm n 2) x)) xs  

expm :: Integer -&gt; Integer -&gt; Integer -&gt; Integer
expm m e b = foldl' (\r (b', _) -&gt; mod (r * b') m) 1 .
             filter (flip testBit 0 . snd) .
             zip (iterate (flip mod m . (^ 2)) b) $
             takeWhile (&gt; 0) $ iterate (`shiftR` 1) e

factor :: Integer -&gt; Integer -&gt; Integer
factor c n = factor' 2 2 1 where
    f x = mod (x * x + c) n
    factor' x y 1 = factor' x' y' (gcd (x' - y') n) where
                        (x', y') = (f x, f $ f y)
    factor' _ _ d = if d == n then factor (c + 1) n else d

factors :: Integer -&gt; StdGen -&gt; [Integer]
factors n g = sort $ fs n where
    fs x | even x      = 2 : fs (div x 2)
         | isPrime x g = [x]
         | otherwise   = f : fs (div x f) where f = factor 1 x

main :: IO ()
main = print . factors (2^98 - 1) =&lt;&lt; getStdGen
</pre>
]]></content:encoded>
	</item>
	<item>
		<title>By: Programming Praxis &#8211; Monte Carlo factorization &#171; Bonsai Code</title>
		<link>http://programmingpraxis.com/2009/06/19/monte-carlo-factorization/#comment-181</link>
		<dc:creator><![CDATA[Programming Praxis &#8211; Monte Carlo factorization &#171; Bonsai Code]]></dc:creator>
		<pubDate>Fri, 19 Jun 2009 13:00:57 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.wordpress.com/?p=765#comment-181</guid>
		<description><![CDATA[[...] Praxis &#8211; Monte Carlo&#160;factorization By Remco Niemeijer  In today’s Programming Praxis problem we have to implement John Pollard&#8217;s factorization algorithm. Our [...]]]></description>
		<content:encoded><![CDATA[<p>[...] Praxis &#8211; Monte Carlo&nbsp;factorization By Remco Niemeijer  In today’s Programming Praxis problem we have to implement John Pollard&#8217;s factorization algorithm. Our [...]</p>
]]></content:encoded>
	</item>
</channel>
</rss>

