<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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:slash="http://purl.org/rss/1.0/modules/slash/"
	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>COME ON CODE ON</title>
	<atom:link href="http://comeoncodeon.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://comeoncodeon.wordpress.com</link>
	<description>A blog about programming and more programming.</description>
	<lastBuildDate>Sat, 28 Jan 2012 11:26:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='comeoncodeon.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>COME ON CODE ON</title>
		<link>http://comeoncodeon.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://comeoncodeon.wordpress.com/osd.xml" title="COME ON CODE ON" />
	<atom:link rel='hub' href='http://comeoncodeon.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Modular Multiplicative Inverse</title>
		<link>http://comeoncodeon.wordpress.com/2011/10/09/modular-multiplicative-inverse/</link>
		<comments>http://comeoncodeon.wordpress.com/2011/10/09/modular-multiplicative-inverse/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 18:59:49 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[euclidean]]></category>
		<category><![CDATA[Euler]]></category>
		<category><![CDATA[fermat]]></category>
		<category><![CDATA[inverse]]></category>
		<category><![CDATA[little]]></category>
		<category><![CDATA[modular]]></category>
		<category><![CDATA[multiplicative]]></category>
		<category><![CDATA[theorem]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=540</guid>
		<description><![CDATA[The modular multiplicative inverse of an integer a modulo m is an integer x such that That is, it is the multiplicative inverse in the ring of integers modulo m. This is equivalent to The multiplicative inverse of a modulo m exists if and only if a and m are coprime (i.e., if gcd(a, m) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=540&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The modular multiplicative inverse of an integer a modulo m is an integer x such that <img src='http://s0.wp.com/latex.php?latex=a%5E%7B-1%7D+%5Cequiv+x+%5Cpmod%7Bm%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{-1} &#92;equiv x &#92;pmod{m}.' title='a^{-1} &#92;equiv x &#92;pmod{m}.' class='latex' /></p>
<p>That is, it is the multiplicative inverse in the ring of integers modulo m. This is equivalent to <img src='http://s0.wp.com/latex.php?latex=ax+%5Cequiv+aa%5E%7B-1%7D+%5Cequiv+1+%5Cpmod%7Bm%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='ax &#92;equiv aa^{-1} &#92;equiv 1 &#92;pmod{m}.' title='ax &#92;equiv aa^{-1} &#92;equiv 1 &#92;pmod{m}.' class='latex' /></p>
<p>The multiplicative inverse of a modulo m exists if and only if a and m are coprime (i.e., if gcd(a, m) = 1).</p>
<p>Let&#8217;s see various ways to calculate Modular Multiplicative Inverse:</p>
<p><strong>1. Brute Force</strong><br />
We can calculate the inverse using a brute force approach where we multiply <em>a</em> with all possible values <em>x</em> and find a <em>x</em> such that <img src='http://s0.wp.com/latex.php?latex=ax+%5Cequiv+1+%5Cpmod%7Bm%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='ax &#92;equiv 1 &#92;pmod{m}.' title='ax &#92;equiv 1 &#92;pmod{m}.' class='latex' /> Here&#8217;s a sample C++ code:<br />
<pre class="brush: cpp;">int modInverse(int a, int m) {
	a %= m;
	for(int x = 1; x &lt; m; x++) {
		if((a*x) % m == 1) return x;
	}
}</pre><br />
The time complexity of the above codes is O(m).</p>
<p><strong>2. Using Extended Euclidean Algorithm</strong><br />
We have to find a number x such that a·x = 1 (mod m). This can be written as well as a·x = 1 + m·y, which rearranges into a·x &#8211; m·y = 1. Since x and y need not be positive, we can write it as well in the standard form, a·x + m·y = 1. </p>
<p>In number theory, Bézout&#8217;s identity for two integers a, b is an expression ax + by = d, where x and y are integers (called Bézout coefficients for (a,b)), such that d is a common divisor of a and b. If d is the greatest common divisor of a and b then Bézout&#8217;s identity ax + by = gcd(a,b) can be solved using Extended Euclidean Algorithm. </p>
<p>The Extended Euclidean Algorithm is an extension to the Euclidean algorithm. Besides finding the greatest common divisor of integers a and b, as the Euclidean algorithm does, it also finds integers x and y (one of which is typically negative) that satisfy Bézout&#8217;s identity<br />
ax + by = gcd(a,b). The Extended Euclidean Algorithm is particularly useful when a and b are coprime, since x is the multiplicative inverse of a modulo b, and y is the multiplicative inverse of b modulo a.</p>
<p>We will look at two ways to find the result of Extended Euclidean Algorithm.</p>
<p><strong>Iterative Method</strong><br />
This method computes expressions of the form <em>r<sub>i</sub></em> = <em>ax<sub>i</sub></em> + <em>by<sub>i</sub></em> for the remainder in each step i of the Euclidean algorithm. Each successive number <em>r<sub>i</sub></em> can be written as the remainder of the division of the previous two such numbers, which remainder can be expressed using the whole quotient <em>q<sub>i</sub></em> of that division as follows:<br />
<img src='http://s0.wp.com/latex.php?latex=r_i+%3D+r_%7Bi-2%7D+-+q_i+r_%7Bi-1%7D.%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='r_i = r_{i-2} - q_i r_{i-1}.&#92;,' title='r_i = r_{i-2} - q_i r_{i-1}.&#92;,' class='latex' /><br />
By substitution, this gives:<br />
 <img src='http://s0.wp.com/latex.php?latex=r_i+%3D+%28ax_%7Bi-2%7D+%2B+by_%7Bi-2%7D%29+-+q_i+%28ax_%7Bi-1%7D+%2B+by_%7Bi-1%7D%29%2C%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='r_i = (ax_{i-2} + by_{i-2}) - q_i (ax_{i-1} + by_{i-1}),&#92;,' title='r_i = (ax_{i-2} + by_{i-2}) - q_i (ax_{i-1} + by_{i-1}),&#92;,' class='latex' />which can be written<br />
 <img src='http://s0.wp.com/latex.php?latex=r_i+%3D+a%28x_%7Bi-2%7D+-+q_i+x_%7Bi-1%7D%29+%2B+b%28y_%7Bi-2%7D+-+q_i+y_%7Bi-1%7D%29.%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='r_i = a(x_{i-2} - q_i x_{i-1}) + b(y_{i-2} - q_i y_{i-1}).&#92;,' title='r_i = a(x_{i-2} - q_i x_{i-1}) + b(y_{i-2} - q_i y_{i-1}).&#92;,' class='latex' /><br />
The first two values are the initial arguments to the algorithm:<br />
 <img src='http://s0.wp.com/latex.php?latex=r_1+%3D+a+%3D+a%5Ctimes1+%2B+b%5Ctimes0%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='r_1 = a = a&#92;times1 + b&#92;times0&#92;,' title='r_1 = a = a&#92;times1 + b&#92;times0&#92;,' class='latex' /><br />
 <img src='http://s0.wp.com/latex.php?latex=r_2+%3D+b+%3D+a%5Ctimes0+%2B+b%5Ctimes1.%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='r_2 = b = a&#92;times0 + b&#92;times1.&#92;,' title='r_2 = b = a&#92;times0 + b&#92;times1.&#92;,' class='latex' /><br />
So the coefficients start out as <em>x<sub>1</sub></em> = 1, <em>y<sub>1</sub></em> = 0, <em>x<sub>2</sub></em> = 0, and <em>y<sub>2</sub></em> = 1, and the others are given by<br />
 <img src='http://s0.wp.com/latex.php?latex=x_i+%3D+x_%7Bi-2%7D+-+q_i+x_%7Bi-1%7D%2C%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='x_i = x_{i-2} - q_i x_{i-1},&#92;,' title='x_i = x_{i-2} - q_i x_{i-1},&#92;,' class='latex' /><br />
 <img src='http://s0.wp.com/latex.php?latex=y_i+%3D+y_%7Bi-2%7D+-+q_i+y_%7Bi-1%7D.%5C%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='y_i = y_{i-2} - q_i y_{i-1}.&#92;,' title='y_i = y_{i-2} - q_i y_{i-1}.&#92;,' class='latex' /><br />
The expression for the last non-zero remainder gives the desired results since this method computes every remainder in terms of a and b, as desired.</p>
<p>So the algorithm looks like,</p>
<ol>
<li>Apply Euclidean algorithm, and let qn(n starts from 1) be a finite list of quotients in the division.</li>
<li>Initialize <em>x<sub>0</sub></em>, <em>x<sub>1</sub></em> as 1, 0, and <em>y<sub>0</sub></em>, <em>y<sub>1</sub></em> as 0,1 respectively.
<ol>
<li>Then for each i so long as <em>q<sub>i</sub></em> is defined,</li>
<li>Compute <em>x<sub>i+1</sub></em> = <em>x<sub>i-1</sub></em> − <em>q<sub>i</sub></em><em>x<sub>i</sub></em></li>
<li>Compute <em>y<sub>i+1</sub></em> = <em>y<sub>i-1</sub></em> − <em>q<sub>i</sub></em><em>y<sub>i</sub></em></li>
<li>Repeat the above after incrementing i by 1.</li>
</ol>
</li>
<li>The answers are the second-to-last of <em>x<sub>n</sub></em> and <em>y<sub>n</sub></em>.</li>
</ol>
<p><pre class="brush: cpp;">/* This function return the gcd of a and b followed by
	the pair x and y of equation ax + by = gcd(a,b)*/
pair&lt;int, pair&lt;int, int&gt; &gt; extendedEuclid(int a, int b) {
	int x = 1, y = 0;
	int xLast = 0, yLast = 1;
	int q, r, m, n;
	while(a != 0) {
		q = b / a;
		r = b % a;
		m = xLast - q * x;
		n = yLast - q * y;
		xLast = x, yLast = y;
		x = m, y = n;
		b = a, a = r;
	}
	return make_pair(b, make_pair(xLast, yLast));
}

int modInverse(int a, int m) {
    return (extendedEuclid(a,m).second.first + m) % m;
}</pre><br />
<strong>Recursive Method</strong><br />
This method attempts to solve the original equation directly, by reducing the dividend and divisor gradually, from the first line to the last line, which can then be substituted with trivial value and work backward to obtain the solution.<br />
Notice that the equation remains unchanged after decomposing the original dividend in terms of the divisor plus a remainder, and then regrouping terms. So the algorithm looks like this:</p>
<ol>
<li>If b = 0, the algorithm ends, returning the solution x = 1, y = 0.</li>
<li>Otherwise:
<ul>
<li>Determine the quotient q and remainder r of dividing a by b using the integer division algorithm.</li>
<li>Then recursively find coefficients s, t such that bs + rt divides both b and r.</li>
<li>Finally the algorithm returns the solution x = t, and y = s − qt.</li>
</ul>
</li>
</ol>
<p>Here&#8217;s a C++ implementation:<br />
<pre class="brush: cpp;">/* This function return the gcd of a and b followed by
	the pair x and y of equation ax + by = gcd(a,b)*/
pair&lt;int, pair&lt;int, int&gt; &gt; extendedEuclid(int a, int b) {
	if(a == 0) return make_pair(b, make_pair(0, 1));
	pair&lt;int, pair&lt;int, int&gt; &gt; p;
	p = extendedEuclid(b % a, a);
	return make_pair(p.first, make_pair(p.second.second - p.second.first*(b/a), p.second.first));
}

int modInverse(int a, int m) {
    return (extendedEuclid(a,m).second.first + m) % m;
}</pre><br />
The time complexity of the above codes is <em>O(log(m)<sup>2</sup>)</em>.</p>
<p><strong>3. Using Fermat&#8217;s Little Theorem</strong><br />
Fermat&#8217;s little theorem states that  if m is a prime and a is an integer co-prime to m, then <em>a<sup>p</sup></em> − 1 will be evenly divisible by m. That is <img src='http://s0.wp.com/latex.php?latex=a%5E%7Bm-1%7D+%5Cequiv+1+%5Cpmod%7Bm%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{m-1} &#92;equiv 1 &#92;pmod{m}.' title='a^{m-1} &#92;equiv 1 &#92;pmod{m}.' class='latex' /> or <img src='http://s0.wp.com/latex.php?latex=a%5E%7Bm-2%7D+%5Cequiv+a%5E%7B-1%7D+%5Cpmod%7Bm%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{m-2} &#92;equiv a^{-1} &#92;pmod{m}.' title='a^{m-2} &#92;equiv a^{-1} &#92;pmod{m}.' class='latex' /> Here&#8217;s a sample C++ code:</p>
<p><pre class="brush: cpp;">/* This function calculates (a^b)%MOD */
int pow(int a, int b, int MOD) {
int x = 1, y = a;
	while(b &gt; 0) {
		if(b%2 == 1) {
			x=(x*y);
			if(x&gt;MOD) x%=MOD;
		}
		y = (y*y);
		if(y&gt;MOD) y%=MOD;
		b /= 2;
	}
	return x;
}

int modInverse(int a, int m) {
    return pow(a,m-2,m);
}</pre><br />
The time complexity of the above codes is O(log(m)).</p>
<p><strong>4. Using Euler&#8217;s Theorem</strong><br />
Fermat&#8217;s Little theorem can only be used if m is a prime. If m is not a prime we can use Euler&#8217;s Theorem, which is a generalization of Fermat&#8217;s Little theorem. According to Euler&#8217;s theorem, if a is coprime to m, that is, gcd(a, m) = 1, then <img src='http://s0.wp.com/latex.php?latex=a%5E%7B%5Cvarphi%28m%29%7D+%5Cequiv+1+%5Cpmod%7Bm%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{&#92;varphi(m)} &#92;equiv 1 &#92;pmod{m}' title='a^{&#92;varphi(m)} &#92;equiv 1 &#92;pmod{m}' class='latex' />, where where φ(m) is Euler Totient Function. Therefore the modular multiplicative inverse can be found directly: <img src='http://s0.wp.com/latex.php?latex=a%5E%7B%5Cvarphi%28m%29-1%7D+%5Cequiv+a%5E%7B-1%7D+%5Cpmod%7Bm%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{&#92;varphi(m)-1} &#92;equiv a^{-1} &#92;pmod{m}' title='a^{&#92;varphi(m)-1} &#92;equiv a^{-1} &#92;pmod{m}' class='latex' />. The problem here is finding φ(m). If we know φ(m), then it is very similar to above method.</p>
<hr />
Now lets take a little different question. Now suppose you have to calculate the inverse of first n numbers. From above the best we can do is O(n log(m)). Can we do any better? Yes.</p>
<p>We can use sieve to find a factor of composite numbers less than n. So for composite numbers inverse(i) = (inverse(i/factor(i)) * inverse(factor(i))) % m, and we can use either Extended Euclidean Algorithm or Fermat&#8217;s Theorem to find inverse for prime numbers. But we can still do better.</p>
<p>a * (m/a) + m % a = 0, or<br />
- (m % a) = a * (m/a).<br />
Dividing both sides by (a * (m % a)), we get<br />
- inverse(a) = (m/a) * inverse(m % a)<br />
inverse(a) = &#8211; (m/a) * inverse(m % a)</p>
<p>Here&#8217;s a sample C++ code:<br />
<pre class="brush: cpp;">vector&lt;int&gt; inverseArray(int n, int m) {
	vector&lt;int&gt; modInverse(n + 1,0);
	modInverse[1] = 1;
	for(int i = 2; i &lt;= n; i++) {
		modInverse[i] = (-(m/i) * modInverse[m % i]) % m + m;
	}
	return modInverse;
}</pre><br />
The time complexity of the above code is O(n).</p>
<p>-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/540/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/540/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/540/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=540&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2011/10/09/modular-multiplicative-inverse/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Combination</title>
		<link>http://comeoncodeon.wordpress.com/2011/07/31/combination/</link>
		<comments>http://comeoncodeon.wordpress.com/2011/07/31/combination/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 12:00:37 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[binomial]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[Euler]]></category>
		<category><![CDATA[factorial]]></category>
		<category><![CDATA[inverse]]></category>
		<category><![CDATA[Lucas]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[multiplication]]></category>
		<category><![CDATA[recurrence]]></category>
		<category><![CDATA[theorem]]></category>
		<category><![CDATA[wilson]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=515</guid>
		<description><![CDATA[In mathematics a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter. More formally a k-combination of a set S is a subset of k distinct elements of S. If the set has n elements the number of k-combinations is equal to the binomial [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=515&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In mathematics a <a href="http://en.wikipedia.org/wiki/Combination">combination</a> is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter. More formally a k-combination of a set S is a subset of k distinct elements of S. If the set has n elements the number of k-combinations is equal to the <a href="http://en.wikipedia.org/wiki/Binomial_coefficient">binomial coefficient</a>. In this post we will see different methods to calculate the binomial.</p>
<p><strong>1. </strong>Using Factorials<br />
We can calculate nCr directly using the factorials.<br />
<strong>nCr = n! / (r! * (n-r)!)</strong><br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;

long long C(int n, int r)
{
    long long f[n];
    f[0]=1;
    for (int i=1;i&lt;=n;i++)
        f[i]=i*f[i-1];
    return f[n]/f[r]/f[n-r];
}

int main()
{
	int n,r,m;
	while (~scanf(&quot;%d%d&quot;,&amp;n,&amp;r))
	{
		printf(&quot;%lld\n&quot;,C(n, min(r,n-r)));
	}
}</pre><br />
But this will work for only factorial below 20 in C++. For larger factorials you can either write big factorial library or use a language like Python. The time complexity is O(n).<br />
If we have to calcuate nCr mod p(where p is a prime), we can calculate factorial mod p and then use modular inverse to find nCr mod p. If we have to find nCr mod m(where m is not prime), we can factorize m into primes and then use <a href="http://en.wikipedia.org/wiki/Chinese_remainder_theorem">Chinese Remainder Theorem</a>(CRT) to find nCr mod m.<br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

/* This function calculates (a^b)%MOD */
long long pow(int a, int b, int MOD)
{
	long long x=1,y=a; 
	while(b &gt; 0)
	{
		if(b%2 == 1)
		{
			x=(x*y);
			if(x&gt;MOD) x%=MOD;
		}
		y = (y*y);
		if(y&gt;MOD) y%=MOD; 
		b /= 2;
	}
	return x;
}

/* 	Modular Multiplicative Inverse
	Using Euler's Theorem
	a^(phi(m)) = 1 (mod m)
	a^(-1) = a^(m-2) (mod m) */
long long InverseEuler(int n, int MOD)
{
	return pow(n,MOD-2,MOD);
}

long long C(int n, int r, int MOD)
{
	vector&lt;long long&gt; f(n,1);
	for (int i=2; i&lt;=n;i++)
		f[i]= (f[i-1]*i) % MOD;
	return (f[n]*((InverseEuler(f[r], MOD) * InverseEuler(f[n-r], MOD)) % MOD)) % MOD;
}

int main()
{    
	int n,r,p;
	while (~scanf(&quot;%d%d%d&quot;,&amp;n,&amp;r,&amp;p))
	{
		printf(&quot;%lld\n&quot;,C(n,r,p));
	}
}</pre></p>
<p><strong>2. </strong>Using Recurrence Relation for nCr<br />
The recurrence relation for nCr is <strong>C(i,k) = C(i-1,k-1) + C(i-1,k)</strong>. Thus we can calculate nCr in time complexity O(n*r) and space complexity O(n*r).<br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

/*
	C(n,r) mod m
	Using recurrence:
	C(i,k) = C(i-1,k-1) + C(i-1,k)
	Time Complexity: O(n*r)
	Space Complexity: O(n*r)
*/

long long C(int n, int r, int MOD)
{
	vector&lt; vector&lt;long long&gt; &gt; C(n+1,vector&lt;long long&gt; (r+1,0));

	for (int i=0; i&lt;=n; i++)
	{
		for (int k=0; k&lt;=r &amp;&amp; k&lt;=i; k++)
			if (k==0 || k==i)
				C[i][k] = 1;
			else
				C[i][k] = (C[i-1][k-1] + C[i-1][k])%MOD;
	}
	return C[n][r];
}
int main()
{
	int n,r,m;
	while (~scanf(&quot;%d%d%d&quot;,&amp;n,&amp;r,&amp;m))
	{
		printf(&quot;%lld\n&quot;,C(n, r, m));
	}
}</pre><br />
We can easily reduce the space complexity of the above solution by just keeping track of the previous row as we don&#8217;t need the rest rows.</p>
<p><pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

/*
	Time Complexity: O(n*r)
	Space Complexity: O(r)
*/
long long C(int n, int r, int MOD)
{
	vector&lt; vector&lt;long long&gt; &gt; C(2,vector&lt;long long&gt; (r+1,0));

	for (int i=0; i&lt;=n; i++)
	{
		for (int k=0; k&lt;=r &amp;&amp; k&lt;=i; k++)
			if (k==0 || k==i)
				C[i&amp;1][k] = 1;
			else
				C[i&amp;1][k] = (C[(i-1)&amp;1][k-1] + C[(i-1)&amp;1][k])%MOD;
	}
	return C[n&amp;1][r];
}

int main()
{
	int n,r,m,i,k;
	while (~scanf(&quot;%d%d%d&quot;,&amp;n,&amp;r,&amp;m))
	{
		printf(&quot;%lld\n&quot;,C(n, r, m));
	}
}</pre></p>
<p><strong>3. </strong>Using expansion of nCr<br />
Since<br />
<strong>
<pre>C(n,k) = n!/((n-k)!k!)
         [n(n-1)...(n-k+1)][(n-k)...(1)]
       = -------------------------------
           [(n-k)...(1)][k(k-1)...(1)]
</pre>
<p></strong><br />
We can cancel the terms: [(n-k)...(1)] as they appear both on top and bottom, leaving:</p>
<pre>
    n (n-1)     (n-k+1)
    - ----- ... -------
    k (k-1)       (1)
</pre>
<p>which we might write as:<br />
<strong>
<pre>C(n,k) = 1,                 if k = 0
       = (n/k)*C(n-1, k-1), otherwise
</pre>
<p></strong><br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;

long long C(int n, int r)
{
	if (r==0) return 1;
    else return C(n-1,r-1) * n / r;
}

int main()
{
	int n,r,m;
	while (~scanf(&quot;%d%d&quot;,&amp;n,&amp;r))
	{
		printf(&quot;%lld\n&quot;,C(n, min(r,n-r)));
	}
}</pre></p>
<p><strong>4. </strong>Using Matrix Multiplication<br />
In the <a href="http://comeoncodeon.wordpress.com/2011/05/08/recurrence-relation-and-matrix-exponentiation/">last post</a> we learned how to use Fast Matrix Multiplication to calculate functions having linear equations in logarithmic time. Here we have the recurrence relation C(i,k) = C(i-1,k-1) + C(i-1,k).<br />
If we take k=3 we can write,<br />
C(i-1,1) + C(i-1,0) = C(i,1)<br />
C(i-1,2) + C(i-1,1) = C(i,2)<br />
C(i-1,3) + C(i-1,2) = C(i,3)<br />
Now on the left side we have four variables C(i-1,0), C(i-1,1), C(i-1,2) and C(i-1,3).<br />
On the right side we have three variables C(i,1), C(i,2) and C(i,3).<br />
We need those two sets to be the same, except that the right side index numbers should be one higher than the left side index numbers. So we add C(i,0) on the right side. NOw let&#8217;s get our all important Matrix.</p>
<pre>(.   .   .   .)  ( C(i-1,0) )   ( C(i,0) )
(.   .   .   .)  ( C(i-1,1) ) = ( C(i,1) )
(.   .   .   .)  ( C(i-1,2) )   ( C(i,2) )
(.   .   .   .)  ( C(i-1,3) )   ( C(i,3) )</pre>
<p>The last three rows are trivial and can be filled from the recurrence equations above.</p>
<pre>(.   .   .   .)  ( C(i-1,0) )   ( C(i,0) )
(1   1   0   0)  ( C(i-1,1) ) = ( C(i,1) )
(0   1   1   0)  ( C(i-1,2) )   ( C(i,2) )
(0   0   1   1)  ( C(i-1,3) )   ( C(i,3) )</pre>
<p>The first row, for C(i,0), depends on what is supposed to happen when k = 0. We know that C(i,0) = 1 for all i when k=0. So the matrix reduces to</p>
<pre>(.   .   .   .)  ( C(i-1,0) )   ( C(i,0) )
(1   1   0   0)  ( C(i-1,1) ) = ( C(i,1) )
(0   1   1   0)  ( C(i-1,2) )   ( C(i,2) )
(0   0   1   1)  ( C(i-1,3) )   ( C(i,3) )</pre>
<p>And this then leads to the general form:</p>
<pre>
               i
(.   .   .   .)  ( C(0,0) )   ( C(i,0) )
(1   1   0   0)  ( C(0,1) ) = ( C(i,1) )
(0   1   1   0)  ( C(0,2) )   ( C(i,2) )
(0   0   1   1)  ( C(0,3) )   ( C(i,3) )</pre>
<p>For example if we wan&#8217;t C(4,3) we just raise the above matrix to the 4th power.</p>
<pre>
              4
(1   0   0   0)  ( 1 )   ( 1 )
(1   1   0   0)  ( 0 ) = ( 4 )
(0   1   1   0)  ( 0 )   ( 6 )
(0   0   1   1)  ( 0 )   ( 4 )</pre>
<p>Here&#8217;s a C++ code.<br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;

/*    
	C(n,r) mod m
	Using Matrix Exponentiation
	Time Complexity: O((r^3)*log(n))
	Space Complexity: O(r*r)
*/

long long MOD;

template&lt; class T &gt;
class Matrix
{
	public:
		int m,n;
		T *data;
		
		Matrix( int m, int n );
		Matrix( const Matrix&lt; T &gt; &amp;matrix );
		
		const Matrix&lt; T &gt; &amp;operator=( const Matrix&lt; T &gt; &amp;A );
		const Matrix&lt; T &gt; operator*( const Matrix&lt; T &gt; &amp;A );
		const Matrix&lt; T &gt; operator^( int P );
		
		~Matrix();
};

template&lt; class T &gt;
Matrix&lt; T &gt;::Matrix( int m, int n )
{
	this-&gt;m = m;
	this-&gt;n = n;
	data = new T[m*n];
}

template&lt; class T &gt;
Matrix&lt; T &gt;::Matrix( const Matrix&lt; T &gt; &amp;A )
{
	this-&gt;m = A.m;
	this-&gt;n = A.n;
	data = new T[m*n];
	for( int i = 0; i &lt; m * n; i++ )
		data[i] = A.data[i];
}

template&lt; class T &gt;
Matrix&lt; T &gt;::~Matrix()
{
	delete [] data;
}

template&lt; class T &gt;
const Matrix&lt; T &gt; &amp;Matrix&lt; T &gt;::operator=( const Matrix&lt; T &gt; &amp;A )
{
	if( &amp;A != this )
	{
		delete [] data;
		m = A.m;
		n = A.n;
		data = new T[m*n];
		for( int i = 0; i &lt; m * n; i++ )
			data[i] = A.data[i];
	}
	return *this;
}

template&lt; class T &gt;
const Matrix&lt; T &gt; Matrix&lt; T &gt;::operator*( const Matrix&lt; T &gt; &amp;A )
{
	Matrix C( m, A.n );
	for( int i = 0; i &lt; m; ++i )
		for( int j = 0; j &lt; A.n; ++j )
		{
			C.data[i*C.n+j]=0;
			for( int k = 0; k &lt; n; ++k )
				C.data[i*C.n+j] = (C.data[i*C.n+j] + (data[i*n+k]*A.data[k*A.n+j])%MOD)%MOD;		
		}
	return C;
}

template&lt; class T &gt;
const Matrix&lt; T &gt; Matrix&lt; T &gt;::operator^( int P )
{
	if( P == 1 ) return (*this);
	if( P &amp; 1 ) return (*this) * ((*this) ^ (P-1));
	Matrix B = (*this) ^ (P/2);
	return B*B;
}

long long C(int n, int r)
{
	Matrix&lt;long long&gt; M(r+1,r+1);
	for (int i=0;i&lt;(r+1)*(r+1);i++)
		M.data[i]=0;
	M.data[0]=1;
	for (int i=1;i&lt;r+1;i++)
	{
		M.data[i*(r+1)+i-1]=1;
		M.data[i*(r+1)+i]=1;
	}
	return (M^n).data[r*(r+1)];
}

int main()
{
	int n,r;
	while (~scanf(&quot;%d%d%lld&quot;,&amp;n,&amp;r,&amp;MOD))
	{
		printf(&quot;%lld\n&quot;,C(n, r));
	}
}</pre></p>
<p><strong>5. </strong>Using the power of prime p in n factorial<br />
The power of prime p in n factorial is given by<br />
<strong><em>ε</em><sub>p</sub> = ⌊n/p⌋ + ⌊n/<em>p</em><sup>2</sup>⌋ + ⌊n/<em>p</em><sup>3</sup>⌋&#8230;</strong><br />
If we call the power of p in n factorial, the power of p in nCr is given by<br />
e = countFact(n,i) &#8211; countFact(r,i) &#8211; countFact(n-r,i)<br />
To get the result we multiply p^e for all p less than n.</p>
<p><pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

/* This function calculates power of p in n! */
int countFact(int n, int p)
{
	int k=0;
	while (n&gt;0)
	{
		k+=n/p;
		n/=p;
	}
	return k;
}

/* This function calculates (a^b)%MOD */
long long pow(int a, int b, int MOD)
{
	long long x=1,y=a; 
	while(b &gt; 0)
	{
		if(b%2 == 1)
		{
			x=(x*y);
			if(x&gt;MOD) x%=MOD;
		}
		y = (y*y);
		if(y&gt;MOD) y%=MOD; 
		b /= 2;
	}
	return x;
}

long long C(int n, int r, int MOD)
{
	long long res = 1;
	vector&lt;bool&gt; isPrime(n,1);
	for (int i=2; i&lt;=n; i++)
		if (isPrime[i])
		{
			for (int j=2*i; j&lt;=n; j+=i)
				isPrime[j]=0;
			int k = countFact(n,i) - countFact(r,i) - countFact(n-r,i);  
			res = (res * pow(i, k, MOD)) % MOD;
		}
	return res;
}

int main()
{
	int n,r,m;
	while (scanf(&quot;%d%d%d&quot;,&amp;n,&amp;r,&amp;m))
	{
		printf(&quot;%lld\n&quot;,C(n,r,m));
	}
}</pre></p>
<p><strong>6. </strong>Using <a href="http://en.wikipedia.org/wiki/Lucas'_theorem">Lucas Theorem</a><br />
For non-negative integers m and n and a prime p, the following congruence relation holds:<br />
<img src='http://s0.wp.com/latex.php?latex=%5Cbinom%7Bm%7D%7Bn%7D%5Cequiv%5Cprod_%7Bi%3D0%7D%5Ek%5Cbinom%7Bm_i%7D%7Bn_i%7D%5Cpmod+p%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='&#92;binom{m}{n}&#92;equiv&#92;prod_{i=0}^k&#92;binom{m_i}{n_i}&#92;pmod p,' title='&#92;binom{m}{n}&#92;equiv&#92;prod_{i=0}^k&#92;binom{m_i}{n_i}&#92;pmod p,' class='latex' /><br />
where<br />
<img src='http://s0.wp.com/latex.php?latex=m%3Dm_kp%5Ek%2Bm_%7Bk-1%7Dp%5E%7Bk-1%7D%2B%5Ccdots+%2Bm_1p%2Bm_0%2C&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='m=m_kp^k+m_{k-1}p^{k-1}+&#92;cdots +m_1p+m_0,' title='m=m_kp^k+m_{k-1}p^{k-1}+&#92;cdots +m_1p+m_0,' class='latex' /><br />
and<br />
<img src='http://s0.wp.com/latex.php?latex=n%3Dn_kp%5Ek%2Bn_%7Bk-1%7Dp%5E%7Bk-1%7D%2B%5Ccdots+%2Bn_1p%2Bn_0&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='n=n_kp^k+n_{k-1}p^{k-1}+&#92;cdots +n_1p+n_0' title='n=n_kp^k+n_{k-1}p^{k-1}+&#92;cdots +n_1p+n_0' class='latex' /><br />
are the base p expansions of m and n respectively.<br />
We only need to calculate nCr only for small numbers (less than equal to p) using any of the above methods.</p>
<p><pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

long long SmallC(int n, int r, int MOD)
{
	vector&lt; vector&lt;long long&gt; &gt; C(2,vector&lt;long long&gt; (r+1,0));

	for (int i=0; i&lt;=n; i++)
	{
		for (int k=0; k&lt;=r &amp;&amp; k&lt;=i; k++)
			if (k==0 || k==i)
				C[i&amp;1][k] = 1;
			else
				C[i&amp;1][k] = (C[(i-1)&amp;1][k-1] + C[(i-1)&amp;1][k])%MOD;
	}
	return C[n&amp;1][r];
}

long long Lucas(int n, int m, int p)
{
	if (n==0 &amp;&amp; m==0) return 1;
	int ni = n % p;
	int mi = m % p;
	if (mi&gt;ni) return 0;
	return Lucas(n/p, m/p, p) * SmallC(ni, mi, p);
}

long long C(int n, int r, int MOD)
{
	return Lucas(n, r, MOD);
}

int main()
{
    
    int n,r,p;
	while (~scanf(&quot;%d%d%d&quot;,&amp;n,&amp;r,&amp;p))
	{
          printf(&quot;%lld\n&quot;,C(n,r,p));
    }
}</pre></p>
<p><strong>7. </strong>Using special n! mod p<br />
We will calculate n factorial mod p and similarly inverse of r! mod p and (n-r)! mod p and multiply to find the result. But while calculating factorial mod p we remove all the multiples of p and write<br />
n!* mod p = 1 * 2 * &#8230; * (p-1) * 1 * 2 * &#8230; * (p-1) * 2 * 1 * 2 * &#8230; * n.<br />
We took the usual factorial, but excluded all factors of p (1 instead of p, 2 instead of 2p, and so on). Lets call this <em>strange factorial</em>.<br />
So <em>strange factorial</em> is really several blocks of construction:<br />
1 * 2 * 3 * &#8230; * (p-1) * i<br />
where i is a 1-indexed index of block taken again without factors p.<br />
The last block could be <em>not</em> full. More precisely, there will be floor(n/p) full blocks and some tail (its result we can compute easily, in O(P)).<br />
The result in each block is multiplication 1 * 2 * &#8230; * (p-1), which is common to all blocks, and multiplication of all <em>strange indices</em> i from 1 to floor(n/p).<br />
But multiplication of all <em>strange indices</em> is really a strange factorial again, so we can compute it recursively. Note, that in recursive calls n reduces exponentially, so this is rather fast algorithm.<br />
Here&#8217;s the algorithm to calculate <em>strange factorial</em>.<br />
<pre class="brush: cpp;">int factMOD(int n, int MOD)
{
	long long res = 1;
	while (n &gt; 1)
	{
		long long cur = 1;
		for (int i=2; i&lt;MOD; ++i)
			cur = (cur * i) % MOD;
		res = (res * powmod (cur, n/MOD, MOD)) % MOD;
		for (int i=2; i&lt;=n%MOD; ++i)
			res = (res * i) % MOD;
		n /= MOD;
	}
	return int (res % MOD);
}</pre><br />
But we can still reduce our complexity.<br />
By <a href="http://en.wikipedia.org/wiki/Wilson's_theorem">Wilson&#8217;s Theorem</a>, we know <img src='http://s0.wp.com/latex.php?latex=%28n-1%29%21%5C+%5Cequiv%5C+-1+%5Cpmod+n&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='(n-1)!&#92; &#92;equiv&#92; -1 &#92;pmod n' title='(n-1)!&#92; &#92;equiv&#92; -1 &#92;pmod n' class='latex' /> for all primes n. SO our method reduces to:<br />
<pre class="brush: cpp;">long long factMOD(int n, int MOD)
{
	long long res = 1;
	while (n &gt; 1)
	{
		res = (res * pow(MOD - 1, n/MOD, MOD)) % MOD;
		for (int i=2, j=n%MOD; i&lt;=j; i++)
			res = (res * i) % MOD;
		n/=MOD;
	}
	return res;
}</pre><br />
Now in the above code we are calculating (-1)^(n/p). If (n/p) is even what we are multiplying by 1, so we can skip that. We only need to consider the case when (n/p) is odd, in which case we are multiplying result by (-1)%MOD, which ultimately is equal to MOD-res. SO our method again reduces to:<br />
<pre class="brush: cpp;">
long long factMOD(int n, int MOD)
{
	long long res = 1; 
	while (n &gt; 0)
	{
		for (int i=2, m=n%MOD; i&lt;=m; i++)
			res = (res * i) % MOD;
		if ((n/=MOD)%2 &gt; 0) 
			res = MOD - res;
	}
	return res;
}</pre><br />
Finally the complete code here:<br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

/* This function calculates power of p in n! */
int countFact(int n, int p)
{
	int k=0;
	while (n&gt;=p)
	{
		k+=n/p;
		n/=p;
	}
	return k;
}

/* This function calculates (a^b)%MOD */
long long pow(int a, int b, int MOD)
{
	long long x=1,y=a; 
	while(b &gt; 0)
	{
		if(b%2 == 1)
		{
			x=(x*y);
			if(x&gt;MOD) x%=MOD;
		}
		y = (y*y);
		if(y&gt;MOD) y%=MOD; 
		b /= 2;
	}
	return x;
}

/* 	Modular Multiplicative Inverse
	Using Euler's Theorem
	a^(phi(m)) = 1 (mod m)
	a^(-1) = a^(m-2) (mod m) */
long long InverseEuler(int n, int MOD)
{
	return pow(n,MOD-2,MOD);
}

long long factMOD(int n, int MOD)
{
	long long res = 1; 
	while (n &gt; 0)
	{
		for (int i=2, m=n%MOD; i&lt;=m; i++)
			res = (res * i) % MOD;
		if ((n/=MOD)%2 &gt; 0) 
			res = MOD - res;
	}
	return res;
}

long long C(int n, int r, int MOD)
{
	if (countFact(n, MOD) &gt; countFact(r, MOD) + countFact(n-r, MOD))
		return 0;

	return (factMOD(n, MOD) *
			((InverseEuler(factMOD(r, MOD), MOD) * 
			InverseEuler(factMOD(n-r, MOD), MOD)) % MOD)) % MOD;
}

int main()
{    
	int n,r,p;
	while (~scanf(&quot;%d%d%d&quot;,&amp;n,&amp;r,&amp;p))
	{
		printf(&quot;%lld\n&quot;,C(n,r,p));
	}
}</pre></p>
<p>-fR0D</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/515/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/515/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/515/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/515/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/515/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/515/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/515/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/515/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=515&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2011/07/31/combination/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Recurrence Relation and Matrix Exponentiation</title>
		<link>http://comeoncodeon.wordpress.com/2011/05/08/recurrence-relation-and-matrix-exponentiation/</link>
		<comments>http://comeoncodeon.wordpress.com/2011/05/08/recurrence-relation-and-matrix-exponentiation/#comments</comments>
		<pubDate>Sun, 08 May 2011 11:56:35 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[complexity]]></category>
		<category><![CDATA[divide-and-conquer]]></category>
		<category><![CDATA[equation]]></category>
		<category><![CDATA[exponentiation]]></category>
		<category><![CDATA[Fibonacci]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[recurrence]]></category>
		<category><![CDATA[relation]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=490</guid>
		<description><![CDATA[Recurrence relations appear many times in computer science. Using recurrence relation and dynamic programming we can calculate the nth term in O(n) time. But many times we need to calculate the nth in O(log n) time. This is where Matrix Exponentiation comes to rescue. We will specifically look at linear recurrences. A linear recurrence is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=490&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recurrence relations appear many times in computer science. Using recurrence relation and dynamic programming we can calculate the <em>n<sup>th</sup></em> term in O(n) time. But many times we need to calculate the <em>n<sup>th</sup></em> in O(log n) time. This is where Matrix Exponentiation comes to rescue.</p>
<p>We will specifically look at linear recurrences. A linear recurrence is a sequence of vectors defined by the equation <em>X<sub>i+1</sub></em> = M <em>X<sub>i</sub></em> for some constant matrix M. So our aim is to find this constant matrix M, for a given recurrence relation.</p>
<p>Let&#8217;s first start by looking at the common structure of our three matrices <em>X<sub>i+1</sub></em>, <em>X<sub>i</sub></em> and M. For a recurrence relation where the next term is dependent on last k terms, <em>X<sub>i+1</sub></em> and <em>X<sub>i+1</sub></em> are matrices of size 1 x k and M is a matrix of size k x k.</p>
<pre>| f(n+1)   |       | f(n)   |
|  f(n)    |       | f(n-1) |
| f(n-1)   | = M x | f(n-2) |
| ......   |       | ...... |
| f(n-k+1) |       | f(n-k) |</pre>
<p>Let&#8217;s look at different type of recurrence relations and how to find M.</p>
<p><strong>1.</strong> Let&#8217;s start with the most common recurrence relation in computer science, The Fibonacci Sequence. <em>F<sub>i+1</sub></em> = <em>F<sub>i</sub></em> + <em>F<sub>i-1</sub></em>.</p>
<pre>| f(n+1) | = M x | f(n)   |
| f(n)   |       | f(n-1) |</pre>
<p>Now we know that M is a 2 x 2 matrix. Let it be</p>
<pre>| f(n+1) | = | a b | x | f(n)   |
| f(n)   |   | c d |   | f(n-1) |</pre>
<p>Now a*f(n) + b*f(n-1) = f(n+1) and c*f(n) + d*f(n-1) = f(n). Solving these two equations we get a=1,b=1,c=1 and d=0. So,</p>
<pre>| f(n+1) | = | 1 1 | x | f(n)   |
| f(n)   |   | 1 0 |   | f(n-1) |</pre>
<p><strong>2.</strong> For recurrence relation f(n) = a*f(n-1) + b*f(n-2) + c*f(n-3), we get</p>
<pre>| f(n+1) | = | a b c | x | f(n)   |
| f(n)   |   | 1 0 0 |   | f(n-1) |
| f(n-1) |   | 0 1 0 |   | f(n-2) |</pre>
<p><strong>3.</strong> What if the recurrence relation is f(n) = a*f(n-1) + b*f(n-2) + c, where c is a constant. We can also add it in the matrices as a state.</p>
<pre>| f(n+1) | = | a b 1 | x | f(n)   |
| f(n)   |   | 1 0 0 |   | f(n-1) |
| c      |   | 0 0 1 |   | c      |</pre>
<p><strong>4.</strong> If a recurrence relation is given like this f(n) = f(n-1) if n is odd, f(n-2) otherwise, we can convert it to f(n) = (n&amp;1) * f(n-1) + (!(n&amp;1)) * f(n-2) and substitute the value accordingly in the matrix.</p>
<pre></pre>
<p><strong>5.</strong>If there are more than one recurrence relation, g(n) = a*g(n-1) + b*g(n-2) + c*f(n), and, f(n) = d*f(n-1) + e*f(n-2). We can still define the matrix X in following way</p>
<pre>| g(n+1) |   | a b c 0 |   | g(n)   |
| g(n)   | = | 1 0 0 0 | x | g(n-1) |
| f(n+2) |   | 0 0 d e |   | f(n+1) |
| f(n+1) |   | 0 0 1 0 |   | f(n)   |</pre>
<p>Now that we have got our matrix M, how are we going to find the nth term.<br />
<em>X<sub>i+1</sub></em> = M <em>X<sub>i</sub></em><br />
(Multiplying M both sides)<br />
M * <em>X<sub>i+1</sub></em> = M * M <em>X<sub>i</sub></em><br />
<em>X<sub>i+2</sub></em> = M^2 <em>X<sub>i</sub></em><br />
..<br />
<em>X<sub>i+k</sub></em> = M^k <em>X<sub>i</sub></em></p>
<p>So all we need now is to find the matrix M^k to find the k-th term. For example in the case of Fibonacci Sequence,</p>
<pre>M^2 = | 2 1 |
      | 1 1 |</pre>
<p>Hence F(2) = 2.</p>
<p>Now we need to learn to find M^k in <em>O</em>(<em>n<sup>3</sup></em> log <em>b</em>) time. The brute force approach to calculate a^b takes O(b) time, but using a recursive divide-and-conquer algorithm takes only O(log b) time:</p>
<ul>
<li>If b = 0, then the answer is 1.</li>
<li>If b = 2k is even, then <em>a<sup>b</sup></em> = (<em>a<sup>k</sup></em>)<em><sup>2</sup></em>.</li>
<li>If b is odd, then <em>a<sup>b</sup></em> = <em>a * a<sup>b-1</sup></em>.</li>
</ul>
<p>We take a similar approach for Matrix Exponentiation. The multiplication part takes the O(<em>n<sup>3</sup></em>) time and hence the overall complexity is <em>O</em>(<em>n<sup>3</sup></em> log <em>b</em>). Here&#8217;s a sample code in C++ using template class:</p>
<p><pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;

template&lt; class T &gt;
class Matrix
{
    public:
		int m,n;
		T *data;

        Matrix( int m, int n );
		Matrix( const Matrix&lt; T &gt; &amp;matrix );

		const Matrix&lt; T &gt; &amp;operator=( const Matrix&lt; T &gt; &amp;A );
        const Matrix&lt; T &gt; operator*( const Matrix&lt; T &gt; &amp;A );
        const Matrix&lt; T &gt; operator^( int P );

		~Matrix();
};

template&lt; class T &gt;
Matrix&lt; T &gt;::Matrix( int m, int n )
{
    this-&gt;m = m;
    this-&gt;n = n;
    data = new T[m*n];
}

template&lt; class T &gt;
Matrix&lt; T &gt;::Matrix( const Matrix&lt; T &gt; &amp;A )
{
    this-&gt;m = A.m;
    this-&gt;n = A.n;
    data = new T[m*n];
    for( int i = 0; i &lt; m * n; i++ )
		data[i] = A.data[i];
}

template&lt; class T &gt;
Matrix&lt; T &gt;::~Matrix()
{
    delete [] data;
}

template&lt; class T &gt;
const Matrix&lt; T &gt; &amp;Matrix&lt; T &gt;::operator=( const Matrix&lt; T &gt; &amp;A )
{
    if( &amp;A != this )
    {
        delete [] data;
        m = A.m;
        n = A.n;
        data = new T[m*n];
        for( int i = 0; i &lt; m * n; i++ )
			data[i] = A.data[i];
    }
    return *this;
}

template&lt; class T &gt;
const Matrix&lt; T &gt; Matrix&lt; T &gt;::operator*( const Matrix&lt; T &gt; &amp;A )
{
	Matrix C( m, A.n );
	for( int i = 0; i &lt; m; ++i )
		for( int j = 0; j &lt; A.n; ++j )
        {
			C.data[i*C.n+j]=0;
			for( int k = 0; k &lt; n; ++k )
				C.data[i*C.n+j] = C.data[i*C.n+j] + data[i*n+k]*A.data[k*A.n+j];
		}
	return C;
}

template&lt; class T &gt;
const Matrix&lt; T &gt; Matrix&lt; T &gt;::operator^( int P )
{
	if( P == 1 ) return (*this);
	if( P &amp; 1 ) return (*this) * ((*this) ^ (P-1));
	Matrix B = (*this) ^ (P/2);
	return B*B;
}

int main()
{
    Matrix&lt;int&gt; M(2,2);
    M.data[0] = 1;M.data[1] = 1;
    M.data[2] = 1;M.data[3] = 0;

	int F[2]={0,1};
    int N;
	while (~scanf(&quot;%d&quot;,&amp;N))
		if (N&gt;1)
			printf(&quot;%lld\n&quot;,(M^N).data[0]);
		else
			printf(&quot;%d\n&quot;,F[N]);
}</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/490/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=490&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2011/05/08/recurrence-relation-and-matrix-exponentiation/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Pollard Rho Brent Integer Factorization</title>
		<link>http://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/#comments</comments>
		<pubDate>Sat, 18 Sep 2010 18:21:17 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[brent]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[pollard]]></category>
		<category><![CDATA[rho]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=478</guid>
		<description><![CDATA[Pollard Rho is an integer factorization algorithm, which is quite fast for large numbers. It is based on Floyd&#8217;s cycle-finding algorithm and on the observation that two numbers x and y are congruent modulo p with probability 0.5 after numbers have been randomly chosen. Algorithm Input : A number N to be factorized Output : [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=478&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Pollard Rho is an integer factorization algorithm, which is quite fast for large numbers. It is based on Floyd&#8217;s cycle-finding algorithm and on the observation that two numbers x and y are congruent modulo p with probability 0.5 after <img src='http://s0.wp.com/latex.php?latex=1.177%5Csqrt%7Bp%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='1.177&#92;sqrt{p}' title='1.177&#92;sqrt{p}' class='latex' /> numbers have been randomly chosen.</p>
<pre><strong>Algorithm</strong>
Input : A number N to be factorized
Output : A divisor of N
If x mod 2 is 0
	return 2

Choose random x and c
y = x
g = 1
while g=1
	x = f(x)
	y = f(f(y))
	g = gcd(x-y,N)
return g
</pre>
<p>Note that this algorithm may not find the factors and will return failure for composite n. In that case, use a different f(x) and try again. Note, as well, that this algorithm does not work when n is a prime number, since, in this case, d will be always 1. We choose f(x) = x*x + c. Here&#8217;s a python implementation :<br />
<pre class="brush: python;">def pollardRho(N):
        if N%2==0:
                return 2
        x = random.randint(1, N-1)
        y = x
        c = random.randint(1, N-1)
        g = 1
        while g==1:             
                x = ((x*x)%N+c)%N
                y = ((y*y)%N+c)%N
                y = ((y*y)%N+c)%N
                g = gcd(abs(x-y),N)
        return g
</pre><br />
In 1980, Richard Brent <a href="http://wwwmaths.anu.edu.au/~brent/pd/rpb051i.pdf">published</a> a faster variant of the rho algorithm. He used the same core ideas as Pollard but a different method of cycle detection, replacing Floyd&#8217;s cycle-finding algorithm with the related Brent&#8217;s cycle finding method. It is quite faster than pollard rho. Here&#8217;s a python implementation :<br />
<pre class="brush: python;">def brent(N):
        if N%2==0:
                return 2
        y,c,m = random.randint(1, N-1),random.randint(1, N-1),random.randint(1, N-1)
        g,r,q = 1,1,1
        while g==1:             
                x = y
                for i in range(r):
                        y = ((y*y)%N+c)%N
                k = 0
                while (k&lt;r and g==1):
                        ys = y
                        for i in range(min(m,r-k)):
                                y = ((y*y)%N+c)%N
                                q = q*(abs(x-y))%N
                        g = gcd(q,N)
                        k = k + m
                r = r*2
        if g==N:
                while True:
                        ys = ((ys*ys)%N+c)%N
                        g = gcd(abs(x-ys),N)
                        if g&gt;1:
                                break
        
        return g    
</pre><br />
-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/478/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/478/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/478/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=478&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Miller Rabin Primality Test</title>
		<link>http://comeoncodeon.wordpress.com/2010/09/18/miller-rabin-primality-test/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/09/18/miller-rabin-primality-test/#comments</comments>
		<pubDate>Sat, 18 Sep 2010 06:53:02 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[fermat]]></category>
		<category><![CDATA[little]]></category>
		<category><![CDATA[miller]]></category>
		<category><![CDATA[primality]]></category>
		<category><![CDATA[prime]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[rabin]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[theorem]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=471</guid>
		<description><![CDATA[Miller Rabin Primality Test is a probabilistic test to check whether a number is a prime or not. It relies on an equality or set of equalities that hold true for prime values, then checks whether or not they hold for a number that we want to test for primality. Theory 1&#62; Fermat&#8217;s little theorem [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=471&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Miller Rabin Primality Test is a probabilistic test to check whether a number is a prime or not. It relies on an equality or set of equalities that hold true for prime values, then checks whether or not they hold for a number that we want to test for primality.</p>
<p><strong>Theory</strong></p>
<p>1&gt; Fermat&#8217;s little theorem states that if p is a prime and 1 ≤ a &lt; p then <img src='http://s0.wp.com/latex.php?latex=a%5E%7Bp-1%7D%5Cequiv1%5Cpmod%7Bp%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{p-1}&#92;equiv1&#92;pmod{p}.' title='a^{p-1}&#92;equiv1&#92;pmod{p}.' class='latex' /><br />
2&gt; If p is a prime and <img src='http://s0.wp.com/latex.php?latex=x%5E2%5Cequiv1%5Cpmod%7Bp%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='x^2&#92;equiv1&#92;pmod{p}' title='x^2&#92;equiv1&#92;pmod{p}' class='latex' /> or <img src='http://s0.wp.com/latex.php?latex=%5Cleft%28x-1%5Cright%29%5Cleft%28x%2B1%5Cright%29%5Cequiv0%5Cpmod%7Bp%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='&#92;left(x-1&#92;right)&#92;left(x+1&#92;right)&#92;equiv0&#92;pmod{p}' title='&#92;left(x-1&#92;right)&#92;left(x+1&#92;right)&#92;equiv0&#92;pmod{p}' class='latex' /> then <img src='http://s0.wp.com/latex.php?latex=x%5Cequiv1%5Cpmod%7Bp%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='x&#92;equiv1&#92;pmod{p}' title='x&#92;equiv1&#92;pmod{p}' class='latex' /> or <img src='http://s0.wp.com/latex.php?latex=x%5Cequiv-1%5Cpmod%7Bp%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='x&#92;equiv-1&#92;pmod{p}.' title='x&#92;equiv-1&#92;pmod{p}.' class='latex' /><br />
3&gt; If n is an odd prime then n-1 is an even number and can be written as <img src='http://s0.wp.com/latex.php?latex=2%5E%7Bs%7D.d&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='2^{s}.d' title='2^{s}.d' class='latex' />. By Fermat&#8217;s Little Theorem either <img src='http://s0.wp.com/latex.php?latex=a%5E%7Bd%7D%5Cequiv1%5Cpmod%7Bn%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{d}&#92;equiv1&#92;pmod{n}' title='a^{d}&#92;equiv1&#92;pmod{n}' class='latex' /> or <img src='http://s0.wp.com/latex.php?latex=a%5E%7B2%5Er%5Ccdot+d%7D%5Cequiv+-1%5Cpmod%7Bn%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{2^r&#92;cdot d}&#92;equiv -1&#92;pmod{n}' title='a^{2^r&#92;cdot d}&#92;equiv -1&#92;pmod{n}' class='latex' /> for some 0 ≤ r ≤  s-1.<br />
4&gt; The Miller–Rabin primality test is based on the contrapositive of the above claim. That is, if we can find an a such that <img src='http://s0.wp.com/latex.php?latex=a%5E%7Bd%7D%5Cnot%5Cequiv1%5Cpmod%7Bn%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{d}&#92;not&#92;equiv1&#92;pmod{n}' title='a^{d}&#92;not&#92;equiv1&#92;pmod{n}' class='latex' /> and <img src='http://s0.wp.com/latex.php?latex=a%5E%7B2%5Er%5Ccdot+d%7D%5Cnot%5Cequiv+-1%5Cpmod%7Bn%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{2^r&#92;cdot d}&#92;not&#92;equiv -1&#92;pmod{n}' title='a^{2^r&#92;cdot d}&#92;not&#92;equiv -1&#92;pmod{n}' class='latex' /> for all 0 ≤ r ≤  s-1 then a is witness of compositeness of n and we can say n is not a prime. Otherwise, n may be a prime.<br />
5&gt; We test our number N for some random a and either declare that N is definitely a composite or probably a prime. The probably that a composite number is returned as prime after k itereations is <img src='http://s0.wp.com/latex.php?latex=4%5E%7B-k%7D.&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='4^{-k}.' title='4^{-k}.' class='latex' /></p>
<p><strong>Algorithm</strong></p>
<pre>
<strong>Input :</strong>A number N to be tested and a variable iteration-the number
of 'a' for which algorithm will test N.
<strong>Output :</strong>0 if N is definitely a composite and 1 if N is probably a prime.

Write N as <img src='http://s0.wp.com/latex.php?latex=2%5E%7Bs%7D.d&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='2^{s}.d' title='2^{s}.d' class='latex' />
For each iteration
	Pick a random a in [1,N-1]
	x = <img src='http://s0.wp.com/latex.php?latex=a%5E%7Bd%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='a^{d}' title='a^{d}' class='latex' /> mod n
	if x =1 or x = n-1
		Next iteration
	for r = 1 to s-1
		x  = <img src='http://s0.wp.com/latex.php?latex=x%5E%7B2%7D&amp;bg=ffffff&amp;fg=1c1c1c&amp;s=0' alt='x^{2}' title='x^{2}' class='latex' /> mod n
		if x = 1
			return false
		if x = N-1
			Next iteration
	return false
return true
</pre>
<p>
Here&#8217;s a python implementation :<br />
<pre class="brush: python;">import random
def modulo(a,b,c):
        x = 1
        y = a
        while b&gt;0:
                if b%2==1:
                        x = (x*y)%c
                y = (y*y)%c
                b = b/2
        return x%c
        
def millerRabin(N,iteration):
        if N&lt;2:
                return False
        if N!=2 and N%2==0:
                return False
        
        d=N-1
        while d%2==0:
                d = d/2
        
        for i in range(iteration):
                a = random.randint(1, N-1)
                temp = d
                x = modulo(a,temp,N)
                while (temp!=N-1 and x!=1 and x!=N-1):
                        x = (x*x)%N
                        temp = temp*2
                
                if (x!=N-1 and temp%2==0):
                        return False
        
        return True
</pre><br />
-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/471/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/471/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/471/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/471/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/471/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/471/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/471/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/471/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=471&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/09/18/miller-rabin-primality-test/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Knuth–Morris–Pratt Algorithm (KMP)</title>
		<link>http://comeoncodeon.wordpress.com/2010/08/29/knuth%e2%80%93morris%e2%80%93pratt-algorithm-kmp/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/08/29/knuth%e2%80%93morris%e2%80%93pratt-algorithm-kmp/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 06:50:47 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[clrs]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Knuth]]></category>
		<category><![CDATA[linear]]></category>
		<category><![CDATA[matching]]></category>
		<category><![CDATA[morris]]></category>
		<category><![CDATA[pratt]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=465</guid>
		<description><![CDATA[Knuth–Morris–Pratt algorithm is the most popular linear time algorithm for string matching. It is little difficult to understand and debug in real time contests. So most programmer&#8217;s have a precoded KMP in their kitty. To understand the algorithm, you can either read it from Introduction to Algorithms (CLRS) or from the wikipedia page. Here&#8217;s a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=465&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Knuth–Morris–Pratt algorithm is the most popular linear time algorithm for string matching. It is little difficult to understand and debug in real time contests. So most programmer&#8217;s have a precoded KMP in their kitty.</p>
<p>To understand the algorithm, you can either read it from Introduction to Algorithms (CLRS) or from the wikipedia <a href="http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm">page</a>. Here&#8217;s a sample C++ code.<br />
<pre class="brush: cpp;">void preKMP(string pattern, int f[])
{
        int m = pattern.length(),k;
        f[0] = -1;
        for (int i = 1; i&lt;m; i++)
        {
                k = f[i-1];
                while (k&gt;=0)
                {
                        if (pattern[k]==pattern[i-1])
                                break;
                        else
                                k = f[k];
                }
                f[i] = k + 1;
        }
}
 
bool KMP(string pattern, string target)
{ 
        int m = pattern.length();
        int n = target.length();
        int f[m];
        
        preKMP(pattern, f);
        
        int i = 0;
        int k = 0;
        
        while (i&lt;n)
        {
                if (k==-1)
                {
                        i++;
                        k = 0;
                }
                else if (target[i]==pattern[k])
                {
                        i++;
                        k++;
                        if (k==m)
                                return 1;
                }
                else
                        k=f[k];
        }
        return 0;
}
</pre><br />
NJOY!<br />
-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/465/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/465/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/465/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/465/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/465/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/465/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/465/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/465/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=465&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/08/29/knuth%e2%80%93morris%e2%80%93pratt-algorithm-kmp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>The Z Algorithm</title>
		<link>http://comeoncodeon.wordpress.com/2010/08/29/the-z-algorithm/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/08/29/the-z-algorithm/#comments</comments>
		<pubDate>Sat, 28 Aug 2010 18:33:16 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[complexity]]></category>
		<category><![CDATA[linear]]></category>
		<category><![CDATA[matching]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=462</guid>
		<description><![CDATA[In this post we will discuss an algorithm for linear time string matching. It is easy to understand and code and is usefull in contests where you cannot copy paste code. Let our string be denoted by S. z[i] denotes the length of the longest substring of S that starts at i and is a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=462&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post we will discuss an algorithm for linear time string matching. It is easy to understand and code and is usefull in contests where you cannot copy paste code.</p>
<p>Let our string be denoted by S.<br />
<em><strong>z[i]</strong></em> denotes the length of the longest substring of S that starts at i and is a prefix of S.<br />
<em><strong>α</strong></em> denotes the substring.<br />
<em><strong>r</strong></em> denotes the index of the last character of α and <em><strong>l</strong></em> denotes the left end of α.</p>
<p>To find whether a pattern(P) of length n is present in a target string(T) of length m, we will create a new string S = P$T where $ is a character present neither in P nor in T. The space taken is n+m+1 or O(m). We will compute z[i] for all i such that 0 &lt; i &lt; n+m+1. If z[i] is equal to n then we have found a occurrence of P at position i &#8211; n &#8211; 1. So we can all the occurrence of P in T in O(m) time. To calculate z[i] we will use the z algorithm.</p>
<p>The Z Algorithm can be read from the section 1.3-1.5 of book <a href="http://books.google.co.in/books?id=STGlsyqtjYMC&amp;lpg=PP1&amp;dq=Algorithms%20on%20Strings%2C%20Trees%2C%20and%20Sequences&amp;pg=PA7#v=onepage&amp;q&amp;f=false">Algorithms on strings, trees, and sequences</a> by Gusfield. Here is a sample C++ code.</p>
<p><pre class="brush: cpp;">bool zAlgorithm(string pattern, string target)
{
	string s = pattern + '$' + target ;
	int n = s.length();
	vector&lt;int&gt; z(n,0);
	
	int goal = pattern.length();
	int r = 0, l = 0, i;
	for (int k = 1; k&lt;n; k++)
	{
		if (k&gt;r)
		{
			for (i = k; i&lt;n &amp;&amp; s[i]==s[i-k]; i++);
			if (i&gt;k)
			{
				z[k] = i - k;
				l = k;
				r = i - 1;
			}
		}
		else
		{
			int kt = k - l, b = r - k + 1;
			if (z[kt]&gt;b)
			{
				for (i = r + 1; i&lt;n &amp;&amp; s[i]==s[i-k]; i++);
				z[k] = i - k;
				l = k;
				r = i - 1;
			}
		}
		if (z[k]==goal)
			return true;
	}
	return false;
}
</pre></p>
<p>NJOY!<br />
-fR0D</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/462/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/462/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/462/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/462/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/462/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/462/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/462/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/462/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=462&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/08/29/the-z-algorithm/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>All Pair Shortest Path (APSP)</title>
		<link>http://comeoncodeon.wordpress.com/2010/08/07/all-pair-shortest-path-apsp/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/08/07/all-pair-shortest-path-apsp/#comments</comments>
		<pubDate>Sat, 07 Aug 2010 08:23:03 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[all]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[DP]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[floyd]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[negative]]></category>
		<category><![CDATA[pair]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[shortest]]></category>
		<category><![CDATA[theory]]></category>
		<category><![CDATA[transitive]]></category>
		<category><![CDATA[warshall]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=453</guid>
		<description><![CDATA[Question : Find shortest paths between all pairs of vertices in a graph. Floyd-Warshall Algorithm It is one of the easiest algorithms, and just involves simple dynamic programming. The algorithm can be read from this wikipedia page. We can also use the algorithm to find the shortest path we can use another matrix called predecessor [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=453&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Question : Find shortest paths between all pairs of vertices in a graph.</strong></p>
<p><strong>Floyd-Warshall Algorithm</strong><br />
It is one of the easiest algorithms, and just involves simple dynamic programming. The algorithm can be read from <a href="http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm">this</a> wikipedia page.</p>
<p><pre class="brush: cpp;">#define SIZE 31
#define INF 1e8
double dis[SIZE][SIZE];
void init(int N)
{
	for (k=0;k&lt;N;k++)
		for (i=0;i&lt;N;i++)
			dis[i][j]=INF;
}
void floyd_warshall(int N)
{
        int i,j,k;
        for (k=0;k&lt;N;k++)
                for (i=0;i&lt;N;i++)
                        for (j=0;j&lt;N;j++)
                                dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
}

int main()
{
	//input size N
	init(N);
	//set values for dis[i][j]
	floyd_warshall(N);
}</pre></p>
<p>We can also use the algorithm to</p>
<ol>
<li>find the shortest path
<ul>
<li>we can use another matrix called predecessor matrix to construct the shortest path.</li>
</ul>
</li>
<li>find negative cycles in a graph.
<ul>
<li>If the value of any of the diagonal elements is less than zero after calling the floyd-warshall algorithm then there is a negative cycle in the graph.</li>
</ul>
</li>
<li>find transitive closure
<ul>
<li>to find if there is a path between two vertices we can use a boolean matrix and use and-&amp; and or-| operators in the floyd_warshall algorithm.</li>
<li>to find the number of paths between any two vertices we can use a similar algorithm.</li>
</ul>
</li>
</ol>
<p>NJOY!!<br />
-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/453/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/453/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/453/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=453&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/08/07/all-pair-shortest-path-apsp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Number of Cycles in a Graph</title>
		<link>http://comeoncodeon.wordpress.com/2010/06/07/number-of-cycles-in-a-graph/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/06/07/number-of-cycles-in-a-graph/#comments</comments>
		<pubDate>Mon, 07 Jun 2010 07:44:33 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[simple]]></category>
		<category><![CDATA[theory]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=438</guid>
		<description><![CDATA[Question : Find the number of simple cycles in a simple graph. Simple Graph &#8211; An undirected graph that has no loops and no more than one edge between any two different vertices. Simple Cycle &#8211; A closed (simple) path, with no other repeated vertices or edges other than the starting and ending vertices. Given [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=438&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Question : Find the number of simple cycles in a simple graph.</strong></p>
<p>Simple Graph &#8211;  An undirected graph that has no loops and no more than one edge between any two different vertices.<br />
Simple Cycle &#8211; A closed (simple) path, with no other repeated vertices or edges other than the starting and ending vertices.</p>
<p>Given a graph of N vertices and M edges, we will look at an algorithm with time complexity O(<em>2</em><sup>N</sup><em>N</em><sup>2</sup>). We will use dynamic programming to do so. Let there be a matrix map, such that map[i][j] is equal to 1 if there is a edge between i and j and 0 otherwise. Let there be another array f[1&lt;&lt;N][N] which denotes the number of simple paths.</p>
<pre>Let,
i denote a subset S of our vertices
k be the smallest set bit of i
then f[i][j] is the number of simple paths from j to k that
contains vertices only from the set S. </pre>
<p>In our algorithm first we will find f[i][j] and then check if there is a edge between k and j, if yes, we can complete every simple path from j to k into a simple cycle and hence we add f[i][j] to our result of total number of simple cycles.Now how to find f[i][j].</p>
<p>For very subset i we iterate through all edges j. Once we have set k, we look for all vertices &#039;l&#039; that can be neighbors of j in our subset S. So if l is a vertex in subset S and there is edge from j to l then f[i][j] = f[i][j] + the number of simple paths from l to i in the subset {S &#8211; j}. Since a simple graph is undirected or bidirectional, we have counted every cycle twice and so we divide our result by 2. Here&#039;s a sample C++ code which takes N, M and the edges as input.<br />
<pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;

#define SIZE 20

bool map[SIZE][SIZE],F;
long long f[1&lt;&lt;SIZE][SIZE],res=0;

int main()
{
    int n,m,i,j,k,l,x,y;
    scanf(&quot;%d%d&quot;,&amp;n,&amp;m);
    for (i=0;i&lt;m;i++)
    {
        scanf(&quot;%d%d&quot;,&amp;x,&amp;y);
        x--;y--;
        if (x&gt;y)
           swap(x,y);
        map[x][y]=map[y][x]=1;
        f[(1&lt;&lt;x)+(1&lt;&lt;y)][y]=1;
    }
    
    for (i=7;i&lt;(1&lt;&lt;n);i++)
    {
        F=1;
        for (j=0;j&lt;n;j++)
            if (i&amp;(1&lt;&lt;j) &amp;&amp; f[i][j]==0)
            {
               if (F)
               {
                  F=0;
                  k=j;
                  continue;
               }
               for (l=k+1;l&lt;n;l++)
               {
                   if (i&amp;(1&lt;&lt;l) &amp;&amp; map[j][l])
                      f[i][j]+=f[i-(1&lt;&lt;j)][l];
               }
               if (map[k][j])
                  res+=f[i][j];
            }
    }
    printf(&quot;%lld\n&quot;,res/2);
}
</pre><br />
NJOY!<br />
-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/438/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/438/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/438/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=438&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/06/07/number-of-cycles-in-a-graph/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
		<item>
		<title>Longest Common Increasing Subsequence (LCIS)</title>
		<link>http://comeoncodeon.wordpress.com/2010/06/01/longest-common-increasing-subsequence-lcis/</link>
		<comments>http://comeoncodeon.wordpress.com/2010/06/01/longest-common-increasing-subsequence-lcis/#comments</comments>
		<pubDate>Tue, 01 Jun 2010 07:17:15 +0000</pubDate>
		<dc:creator>fR0DDY</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[common]]></category>
		<category><![CDATA[increasing]]></category>
		<category><![CDATA[lcis]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[subsequence]]></category>

		<guid isPermaLink="false">http://comeoncodeon.wordpress.com/?p=431</guid>
		<description><![CDATA[Given 2 sequences of integers, we need to find a longest sub-sequence which is common to both the sequences, and the numbers of such a sub-sequence are in strictly increasing order. For example, 2 3 1 6 5 4 6 1 3 5 6 the LCIS is 3 5 6. The sequence a1, a2, &#8230;, an is called increasing, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=431&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Given 2 sequences of integers, we need to find a longest sub-sequence which is common to both the sequences, and the numbers of such a sub-sequence are in strictly increasing order.</strong><br />
For example,<br />
2 3 1 6 5 4 6<br />
1 3 5 6<br />
the LCIS is 3 5 6.</p>
<p>The sequence <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, &#8230;, <em>a</em><sub><em>n</em></sub> is called increasing, if <em>a</em><sub><em>i</em></sub>&lt;<em>a</em><sub><em>i</em>+1</sub> for <em>i</em>&lt;<em>n</em>.The sequence <em>s</em><sub>1</sub>, <em>s</em><sub>2</sub>, &#8230;, <em>s</em><sub><em>k</em></sub> is called the subsequence of the sequence <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, &#8230;, <em>a</em><sub><em>n</em></sub>, if there exist such a set of indexes 1 ≤ <em>i</em><sub>1</sub> &lt; <em>i</em><sub>2</sub> &lt; &#8230; &lt; <em>i</em><sub><em>k</em></sub> ≤ <em>n</em> that <em>a</em><sub><em>i</em><sub><em>j</em></sub></sub> = <em>s</em><sub><em>j</em></sub>. In other words, the sequence <em>s</em> can be derived from the sequence <em>a</em> by crossing out some elements.</p>
<p>A nice tutorial on the algorithm is given on CodeChef blog <a href="http://blog.codechef.com/2009/05/19/211/" target="_blank">here</a>. If you read the blog you can see that instead of looking for LCIS in a candidate matrix, we can keep an array that stores the length of LCIS ending at that particular element. Also we keep a lookup previous array that gives the index of the previous element of the LCIS, which is used to reconstruct the LCIS. </p>
<p>For every element in the two arrays<br />
1&gt; If they are equal we check whether the LCIS formed will be bigger than any previous such LCIS ending at that element. If yes we change the data.<br />
2&gt; If the jth element of array B is smaller than ith element of array A, we check whether it has a LCIS greater than current LCIS length, if yes we store it as previous value and it&#8217;s LCIS length as current LCIS length.</p>
<p>Here&#8217;s a C++ code.</p>
<p><pre class="brush: cpp;">#include&lt;iostream&gt;
using namespace std;
#include&lt;vector&gt;

void LCIS(vector&lt;int&gt; A, vector&lt;int&gt; B)
{
    int N=A.size(),M=B.size(),i,j;
    vector&lt;int&gt; C(M,0);
    vector&lt;int&gt; prev(M,0);
    vector&lt;int&gt; res;
    
    for (i=0;i&lt;N;i++)
    {
        int cur=0,last=-1;
        for (j=0;j&lt;M;j++)
        {
            if (A[i]==B[j] &amp;&amp; cur+1&gt;C[j])
            {
               C[j]=cur+1;
               prev[j]=last;
            }
            if (B[j]&lt;A[i] &amp;&amp; cur&lt;C[j])
            {
               cur=C[j];
               last=j;
            }
        }
    }
    
    int length=0,index=-1;
    for (i=0;i&lt;M;i++)
        if (C[i]&gt;length)
        {
           length=C[i];
           index=i;
        }
    printf(&quot;The length of LCIS is %d\n&quot;,length);
    if (length&gt;0)
    {
       printf(&quot;The LCIS is \n&quot;);
       while (index!=-1)
       {
             res.push_back(B[index]);
             index=prev[index];
       }
       reverse(res.begin(),res.end());
       for (i=0;i&lt;length;i++)
           printf(&quot;%d%s&quot;,res[i],i==length-1?&quot;\n&quot;:&quot; &quot;);
    }
}


int main()
{
    int n,m,i;
    scanf (&quot;%d&quot;, &amp;n);
    vector&lt;int&gt; A(n,0);
    for (i = 0; i &lt; n; i++)
        scanf (&quot;%d&quot;, &amp;A[i]);
    scanf (&quot;%d&quot;, &amp;m);
    vector&lt;int&gt; B(m,0);
    for (i = 0; i &lt; m; i++)
        scanf (&quot;%d&quot;, &amp;B[i]);
    LCIS(A,B);
}
</pre><br />
NJOY!<br />
-fR0DDY</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/comeoncodeon.wordpress.com/431/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/comeoncodeon.wordpress.com/431/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/comeoncodeon.wordpress.com/431/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/comeoncodeon.wordpress.com/431/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/comeoncodeon.wordpress.com/431/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/comeoncodeon.wordpress.com/431/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/comeoncodeon.wordpress.com/431/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/comeoncodeon.wordpress.com/431/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=comeoncodeon.wordpress.com&amp;blog=6510929&amp;post=431&amp;subd=comeoncodeon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://comeoncodeon.wordpress.com/2010/06/01/longest-common-increasing-subsequence-lcis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/60401b326632d9f7def9f258670961b4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">fR0DDY</media:title>
		</media:content>
	</item>
	</channel>
</rss>
