The method of prime number, Prime Rabin test and fast power modulus

Source: Internet
Author: User
Tags modulus

Prime number Sieve method to produce the prime list within num

public static int  makeprimes (int primes[], int num)
	{
		int i, J, CNT;
		Primes[0] = 2;
		PRIMES[1] = 3;
		for (i = 5, cnt = 2; i < num; i + = 2)
		{
			Boolean flag = true;
			for (j = 1; primes[j]*primes[j] <= i; ++j)
			{
				if (i%primes[j] = = 0)
				{
					flag = false; 
					break;
				}
			}
			if (flag) primes[cnt++] = i;
		}
		return cnt;
	}


According to the Prime number table quickly determine whether the prime, as long as the table to sqrt (n), you can quickly determine whether the numbers within N is a prime


public static Boolean  isprime (int primes[], int n)
	{
		if (n < 2) 
			return false;
		for (int i = 0; primes[i]*primes[i] <= n; i++)
			if (n%primes[i] = = 0) 
				return false;
		return true;
	}




Fast Power-Take mode

public static long Pow_mod (long A,long i,long N)
	{
		if (i==0)
			return 1%n;
		Long Temp=pow_mod (A, i>>1, n);
		temp= (temp*temp)%n;
		if ((i&1)!=0)
			temp= (temp*a)%n;
		return temp;
	}


Prime number Test


Because of the intermediate variables of the Long*long type, it is only possible to test the int range, which requires a larger range to be used Bigdecimal/biginteger

public static Boolean IsPrime (long N)
	{
		if (n<2)
			return false;
		Int[] a={2,3,5,7,11,61}; Test set for
		(int i=0;i<a.length;i++)
			if (!test (n, A[i], n-1))
				return false;
		return true;
	}
	
	public static Boolean test (long N,long a,long D)
	{
		if (n==2)
			return true;
		if (n==a)
			return true;
		if ((n&1) ==0)
			return false;
		while ((d&1) ==0)
			d=d>>1;
		Long T =pow_mod (A, D, N);
		while ((d!=n-1) && (t!=1) && (t!=n-1))
		{
			t= (t*t)%n;
			d=d<<1;
		}
		
		Return (t==n-1| | (d&1) ==1);
	}
	
	public static long Pow_mod (long A,long i,long N)
	{
		if (i==0)
			return 1%n;
		Long Temp=pow_mod (A, i>>1, n);
		temp= (temp*temp)%n;
		if ((i&1)!=0)
			temp= (temp*a)%n;
		return temp;
	}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.