Randomized Algorithms :Miller-Rabins Primality Testing

Friday 11 January 2013
A Randomized Algorithm is one in which we use a randomizer or some kind of random number.Some decisions made in the algorithm depend on the output of the randomizer.Hence they have different runtime each time they are run even if the input is correct.
      Randomized algorithms can be divided into two categories:
Las Vegas Algorithms : These algorithms always give the correct output, however their runtime differ based on the output of the randomizer
Monte Carlo Algorithms: These algorithms give the correct answer for most of the cases however they may give incorrect answers for a small percent of values.

Primality testing using Miller-Rabin's Method: This algorithm makes use of Fermat theorem i.e. if n is prime than a^(n-1) %n=1 for any a<n.

Th2: The equation x^2%n=1 has exactly two solutions namely 1 and n-1
Th3: The equation x^2(mod n)=1 has roots other than 1 and n-1 then n is composite

The algorithm fails for some composite numbers (Carmichael numbers) for which every a that is less than and relatively prime to n will satisfy Fermats theorem.e.g 561 and 1105

Implementation:

int prime(int n,int alpha)
{
  int q=n-1;int i;
  int up=(int)alpha*log(n);
  int m,y,a,z,x;
  for(i=0;i<up;i++)
    {
      m=q;y=1;
      a=rand()%q+1;
      //choosing a random number in the range [1,n-1]
      z=a;
      //compute a^n-1 mod n
      while(m>0)
    {
      while(m%2==0)
        {
          x=z;
          z=(z*z)%n;
          if((z==1)&&(x!=1)&&(x!=q))
        return 0;
          m=(int)m/2;
        }
      m=m-1;y=(y*z)%n;
    }
      if(y!=1)
    return 0;
      //if a^n-1 mod n is not 1 n is not a prime
    }
  return 1;
}



Copyright @ 2013 code-craft. Designed by Templateism | MyBloggerLab