Beispiel #1
0
int PrimeFactor(long x)
{
  /* Start with the first prime */
  int prime = 2;

  if (IsPrime(x))
  {
    printf("Found prime factor %ld\n", x);
    return x;
  }

  /* Find the next prime that divides cleanly */
  while ( x % prime != 0 )
    prime = NextPrime(prime);

  printf("Factoring %ld, found prime %d\n", x, prime);

  x /= prime; /* Divide the value by the prime factor */

  /* Shall we continue? */
  if (!IsPrime(x))
    PrimeFactor(x);
  else
    printf("Found prime factor %ld\n", x);

  return x;
}
Beispiel #2
0
void TestScheduler(const char* msg, const PrimeMap& value, time_sec serialTime)
{
	ticks_t start = now();
	SCHEDULER scheduler(CoreCount);
	std::map<std::size_t, std::size_t> tasks;
	for (std::size_t i = 0; i < Count; i++)
	{
#ifdef VOID_TEST
		tasks[i] = scheduler.add_task([i]() -> void {Test(i); });
		tasks[MaxNum - i] = scheduler.add_task([i]() -> void {Test(MaxNum - i); });
#else
		tasks[i] = scheduler.add_task([i]() -> bool { return IsPrime(i); });
		tasks[MaxNum - i] = scheduler.add_task([i]() -> bool { return IsPrime(MaxNum - i); });
#endif
	}

	for (auto i = tasks.begin(); i != tasks.end(); ++i)
	{
#ifdef VOID_TEST
        scheduler.get_task_result(i->second);
#else
		if (value.at(i->first) != scheduler.get_task_result(i->second))
			throw 0;
#endif
	}
	time_sec parallelTime = ticks_to_time(now() - start);
	std::cout << msg << " time = " << parallelTime << " [s]  -  Serial time portion = " << parallelTime / (serialTime / 100.0) << " [%]" << std::endl;
	std::cout << msg << " calculation correct" << std::endl;
}
Beispiel #3
0
// Tests negative input.
TEST(IsPrimeTest, Negative) {
  // This test belongs to the IsPrimeTest test case.

  EXPECT_FALSE(IsPrime(-1));
  EXPECT_FALSE(IsPrime(-2));
  EXPECT_FALSE(IsPrime(INT_MIN));
}
Beispiel #4
0
int main()
{
#ifdef VOID_TEST
    std::cerr << "Void test." << std::endl;
#else
    std::cerr << "Int test." << std::endl;
#endif
	ticks_t start = now();
	PrimeMap value;
	for (std::size_t i = 0; i < Count; i++)
	{
#ifdef VOID_TEST
		Test(i);
		Test(MaxNum - i);
#else
		value[i] = IsPrime(i);
		value[MaxNum - i] = IsPrime(MaxNum - i);
#endif
	}
	time_sec serialTime = ticks_to_time(now() - start);
	std::cout << "Serial time = " << serialTime << std::endl;

#ifdef VOID_TEST
	TestScheduler<Scheduler<void, std::function<void(void)>>>("Scheduler", value, serialTime);
#else
	TestScheduler<Scheduler<bool, std::function<bool(void)> > >("Scheduler", value, serialTime);
#endif

	system("pause");
	return 0;
}
Beispiel #5
0
bool DSA::GeneratePrimes(const byte *seedIn, unsigned int g, int &counter,
						  Integer &p, unsigned int L, Integer &q, bool useInputCounterValue)
{
	assert(g%8 == 0);

	SHA sha;
	SecByteBlock seed(seedIn, g/8);
	SecByteBlock U(SHA::DIGESTSIZE);
	SecByteBlock temp(SHA::DIGESTSIZE);
	SecByteBlock W(((L-1)/160+1) * SHA::DIGESTSIZE);
	const int n = (L-1) / 160;
	const int b = (L-1) % 160;
	Integer X;

	sha.CalculateDigest(U, seed, g/8);

	for (int i=g/8-1, carry=true; i>=0 && carry; i--)
		carry=!++seed[i];

	sha.CalculateDigest(temp, seed, g/8);
	xorbuf(U, temp, SHA::DIGESTSIZE);

	U[0] |= 0x80;
	U[SHA::DIGESTSIZE-1] |= 1;
	q.Decode(U, SHA::DIGESTSIZE);

	if (!IsPrime(q))
		return false;

	int counterEnd = useInputCounterValue ? counter+1 : 4096;

	for (int c = 0; c < counterEnd; c++)
	{
		for (int k=0; k<=n; k++)
		{
			for (int i=g/8-1, carry=true; i>=0 && carry; i--)
				carry=!++seed[i];
			if (!useInputCounterValue || c == counter)
				sha.CalculateDigest(W+(n-k)*SHA::DIGESTSIZE, seed, g/8);
		}
		if (!useInputCounterValue || c == counter)
		{
			W[SHA::DIGESTSIZE - 1 - b/8] |= 0x80;
			X.Decode(W + SHA::DIGESTSIZE - 1 - b/8, L/8);
			p = X-((X % (2*q))-1);

			if (p.GetBit(L-1) && IsPrime(p))
			{
				counter = c;
				return true;
			}
		}
	}
	return false;
}
Beispiel #6
0
void GenerateModulus(unsigned long * P, unsigned long * Q)
{
	while(1)
	{
		if (!IsPrime(*P) || *P == 0|| *P == *Q )
			*P = (unsigned long)GenerateRandomNumber(MIN,MAX);
		if (!IsPrime(*Q) || *Q == 0)
			*Q = (unsigned long)GenerateRandomNumber(MIN,MAX);
		if (IsPrime(*P) && IsPrime(*Q) && *Q != *P)
			break;
	}
}
int main( void ) {
	unsigned long long a = 10, b = 40;
	int prime = 367;
	int not_prime = 244;

	Prime( a, b );
	printf( "Primes in [%llu, %llu]: %llu\n", a, b, AnzPrime( a, b ) );
	printf( "Is %d a prime? -> %d\n", prime, IsPrime( prime ) );
	printf( "Is %d a prime? -> %d\n", not_prime, IsPrime( not_prime ) );

	return EXIT_SUCCESS;
}
Beispiel #8
0
void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned int qbits)
{
	// no prime exists for delta = -1, qbits = 4, and pbits = 5
	assert(qbits > 4);
	assert(pbits > qbits);

	if (qbits+1 == pbits)
	{
		Integer minP = Integer::Power2(pbits-1);
		Integer maxP = Integer::Power2(pbits) - 1;
		bool success = false;

		while (!success)
		{
			p.Randomize(rng, minP, maxP, Integer::ANY, 6+5*delta, 12);
			PrimeSieve sieve(p, STDMIN(p+PrimeSearchInterval(maxP)*12, maxP), 12, delta);

			while (sieve.NextCandidate(p))
			{
				assert(IsSmallPrime(p) || SmallDivisorsTest(p));
				q = (p-delta) >> 1;
				assert(IsSmallPrime(q) || SmallDivisorsTest(q));
				if (FastProbablePrimeTest(q) && FastProbablePrimeTest(p) && IsPrime(q) && IsPrime(p))
				{
					success = true;
					break;
				}
			}
		}

		if (delta == 1)
		{
			// find g such that g is a quadratic residue mod p, then g has order q
			// g=4 always works, but this way we get the smallest quadratic residue (other than 1)
			for (g=2; Jacobi(g, p) != 1; ++g) {}
			// contributed by Walt Tuvell: g should be the following according to the Law of Quadratic Reciprocity
			assert((p%8==1 || p%8==7) ? g==2 : (p%12==1 || p%12==11) ? g==3 : g==4);
		}
		else
		{
			assert(delta == -1);
			// find g such that g*g-4 is a quadratic non-residue, 
			// and such that g has order q
			for (g=3; ; ++g)
				if (Jacobi(g*g-4, p)==-1 && Lucas(q, g, p)==2)
					break;
		}
	}
int main()
{
	
	long long int fac1;
	long long int other_factor,after_e,g1;
	long long int p, q, n;
	int flag;
	
	long long int t;
	
	double start, end, time;
	printf("Enter the prime number\n");
	scanf("%lld",&p);
	
	flag = IsPrime(p);
	if( flag == 0)
	{
		printf("wrong input");
		exit(0);
	}
	printf("Enter another prime number\n");
	scanf("%lld",&q);
	flag = IsPrime(q);
	if(flag ==0 || p==q)
	{
		printf("wrong input");
		exit(0);
	}
	

	n= p*q;
	t = (p-1)*(q-1);
	
	//decrypt(after_e);
	g1 = gcd( p, q);
    fac1 = pollard(n);
	printf("Factor is : %lld", fac1);
	other_factor = n/ fac1;
	
	after_e = (fac1-1)*(other_factor-1);
	start = clock();
	
	end = clock(); 
	time = (double) (end-start)/CLOCKS_PER_SEC;
	printf("\nTime taken = %f\n", time);
	
	return 0;
}
Beispiel #10
0
unsigned int NextPrime(unsigned int current)
{
  /* Iterate to the next prime number */
  while (!IsPrime(++current));

  return current;
}
Beispiel #11
0
// Requires e and n
bool RSA32::CrackPrivateKey( )
{
    // Resources:
    // http://stackoverflow.com/questions/4078902/cracking-short-rsa-keys

    // p and q might get flipped, but it doesn't matter at al.

    // Get the square root of n and floor it.
    unsigned int temp_p = static_cast<unsigned int>( floor( sqrt( static_cast<double>( m_n ) ) ) );
    bool found_p = false;

    // Get the closest prime below temp_p;
    while( temp_p >= 2 )
    {
        if( IsPrime( temp_p ) )
        {
            found_p = true;
            break;
        }

        // Decrease p by 2.
        temp_p--;
    }

    // Error check if we didn't find p
    if( !found_p )
    {
        return false;
    }

    // Reset the found p flag and do another last test in order to make sure we've found p
    found_p = false;

    while( temp_p >= 2 )
    {
        // n mod temp_p should be 0 if we've found p
        if( m_n % temp_p == 0 )
        {
            m_p = temp_p;
            found_p = true;
            break;
        }

        // Decrease p by 2.
        temp_p -= 2;
    }

    // Error check if we didn't find p, once again.
    if( !found_p )
    {
        return false;
    }

    // Calculate the second prime q and then finall z as well.
    m_q = m_n / m_p;
    m_z = ( m_p - 1 ) * ( m_q - 1 );

    // The last thing to do is to calculate the private key d
    return CalculatePrivateKey( );
}
Beispiel #12
0
int main()
{
    int i;
    for(i=2;i<=1000;i++)
        IsPrime(i);
    return 0;
}
Beispiel #13
0
int main()
{
	int n;
	int i,j = 0;
	n = GetNumber();
	printf("The primes between 2 and %d are :\n",n);
	for(i = 2;i * i< n;++i )//使循环减少n - 根号n + 1次
	{
		if(IsPrime(i))
		{
			printf("%d ",i);
			j++;
			if(j%5 == 0)
			{
				printf("\n");
			}
		}
	}
		if(j%5 != 0)
		{
			printf("\n");
		}
	return 0;

}
Beispiel #14
0
int countPrimes(int n)
{
	int *Buffer;
	int Number, i, j;

	Buffer = malloc(sizeof(int) * n);
	memset(Buffer, 0, n * sizeof(int));

	for (i = 2; i * i <= n; ++i)
	{
		if (!IsPrime(i))
			continue;
			
		for (j = i; j * i < n; ++j)
		{
			Buffer[i * j] = 1;
		}
	}

	for (Number = 0, i = 2; i < n; ++i)
	{
		if (Buffer[i] == 0)
			Number++;
	}

	free(Buffer);
	return Number;
}
void main()
{
	while(true)
	{
		int productMax,numerator,denominator;
		scanf("%d%d%d",&productMax,&numerator,&denominator);
		if(productMax==0)
			break;
		int widthMostSuitable=0,lengthMostSuitable=0;
		for(int width=2;width*width<productMax;width++)
			if(IsPrime(width))
			{
				int upperBoundA=width*denominator/numerator;
				int upperBoundB=productMax/width;
				int upperBound=min(upperBoundA,upperBoundB);
				int length=MaxPrime(upperBound);
				if(length!=UNEXIST && width*length>widthMostSuitable*lengthMostSuitable)
				{
					widthMostSuitable=width;
					lengthMostSuitable=length;
				}
			}
		printf("%d %d\n",widthMostSuitable,lengthMostSuitable);
	}
}
int MaxPrime(int upperBound)
{
	for(int i=upperBound;i>=2;i--)
		if(IsPrime(i))
			return i;
	return UNEXIST;
}
Beispiel #17
0
bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level)
{
	bool pass = IsPrime(p) && RabinMillerTest(rng, p, 1);
	if (level >= 1)
		pass = pass && RabinMillerTest(rng, p, 10);
	return pass;
}
Beispiel #18
0
uint64_t GetPrime(uint16_t n) {
    // error check: terminate program if n is 0
    if (n == 0) {
        fprintf(stderr, "error: GetPrime(0) called!\n");
        exit(EXIT_FAILURE);
    }

    uint64_t checknext = 2;
    // Advance checknext and count prime values as they are discovered.
    // When the nth one is found, return it.
    while (1) {
        // If checknext is prime, return it if it is the requested one,
        // otherwise decrease count of primes remaining to be discovered
        if (IsPrime(checknext)) {
            if (n == 1) {
                return checknext;
            }
            n--;
        }

        // terminate program if we've reached the largest positive integer
        if (checknext == UINT64_MAX) {
            fprintf(stderr, "Hit the largest uint64_t, aborting.\n");
            exit(EXIT_FAILURE);
        }

        // advance to next trial number
        checknext++;
    }

    // Should never get here.
    return 0;
}
void generator()
{
    primes = malloc(sizeof(int)*LIMIT);
    numbers = malloc(sizeof(int)*LIMIT);

    // Array of natural numbers
    for (i=0;i<LIMIT;i++){
        numbers[i]=i+2;
    }

    for (i=0;i<LIMIT;i++)
    {
        if (numbers[i]!=-1)
        {
            for (j=0;j<LIMIT;j++)
            {
                if(!IsPrime(numbers[j]))
            	numbers[j]=-1;

            }
        }
    }

    // Create the array of all prime numbers
    j = 0;
    for (i=0;i<LIMIT&&j<LIMIT;i++)
        if (numbers[i]!=-1)
        {
            primes[j++] = numbers[i];
        }

    nprime = j-1;
}
int CoprimeTest(int numOne, int numTwo) {
	
	int i = 0;
	int areCoprime = TRUE; // disprove whether numbers are Coprime
	int larger = 0;
	int smaller = 0;
	
	// determine that larger of the two numbers
	if(numOne >= numTwo) {
		larger = numOne;
		smaller = numTwo;
	} else {
		larger = numTwo;
		smaller = numOne;
	}
	
	for(i = 1; i <= larger; i++) {
		// find a prime factor for numOne
		if(larger % i == 0 && IsPrime(i)) {
			// determine if numTwo is divisible by the candidate prime
			if(smaller % i == 0) {
				areCoprime = FALSE;
			}
		}
	}

	// return the result
	return areCoprime;

} // end - CoprimeTest()
Beispiel #21
0
unsigned long FactorPrivateKey(unsigned long N, unsigned long E)
{
	unsigned long i = 2;
	unsigned long P = 0;
	unsigned long Q = 0;
	unsigned long D = 0;

	for(i; i < N; i++)
	{
		if (IsPrime(i) && N % i == 0)
		{
			Q = i;
			P = N / Q; 
			if (P != Q) 
			{
				break;
			}
		}
	}

	if (P != 0 && Q != 0)
	{
		i = 1;

		while ((1+ i*(P*Q - P - Q + 1)) % E != 0)
		{
			i++;
		}

		D = (1+ i*(P*Q - P - Q + 1))/E;

		printf("Private Key Factored (%lu, %lu)\n", N, D);
	}
	return D;
}
Beispiel #22
0
void PrimeDialog::calculate() {
    bool bPrime = IsPrime(primeEdit->text().toInt());
    showLabel->setText(QString("Number ")
                       .append(primeEdit->text())
                       .append(" is ")
                       .append(bPrime?"":"not ")
                       .append("prime number!"));
}
Beispiel #23
0
static unsigned
GetMaxPrimNum(unsigned n)
{
    for (int i = n; i >= 2; i--)
        if (IsPrime(i))
            return i;
    return -1;
}
Beispiel #24
0
static bool
FillBlock(unsigned block_index)
{
    // TODO: make it more efficient
    unsigned up_limit = (block_index + 1) * units_of_block * bits_of_unit;
    for (unsigned i = 2; i < up_limit; i++) {
	if (IsPrime(i)) {
	    unsigned composite_num = i * 2;
	    while (composite_num < up_limit) {
		UnsetPrime(composite_num);
		assert(!IsPrime(composite_num));
		composite_num += i;
	    }
	}
    }

    return true;
}
Beispiel #25
0
 // Brute force next prime integer (reasonably quick I think)
 // http://stackoverflow.com/questions/4475996/given-prime-number-n-compute-the-next-prime
 // Answer 7 by Howard Hinnant --> Implementation 4
 std::size_t NextPrime(std::size_t x) {
   if (x <= 2)
     return 2;
   if (!(x & 1))
     ++x;
   for (; !IsPrime(x); x += 2)
     ;
   return x;
 }
Beispiel #26
0
inline Int Primes::NextPrime(Int i)
{
	Int si = i;

	while(!IsPrime(si))
		si++;

	return si;
}
Beispiel #27
0
int main(){
	int n;
	scanf("%d", &n);
	int i;
	for(i=1; i<=n; i++)
		if (IsPrime(i))
			printf("%d, ", i);	
	printf("\n");
return 0;
}
Beispiel #28
0
int main()
{
    int n;
    Sieve();
    scanf("%d", &n);
    if(IsPrime(n)) {
        printf("%d\n", 1);
    } else {
        char haveTow = 0;
        for(int i = 0; i < PrimeCnt; ++i) {
            if(IsPrime(n - Prime[i])) {
                haveTow = 1;
                break;
            }
        }
        printf("%d\n", haveTow ? 2 : 3);
    }
    return 0;
}
int GetThePrimeBelow1000000CanBeWrittenAsTheSumOfTheMostConsecutivePrimes()
	{
	int* buffer = new int[COUNT];
	int realCount = GetPrimeList(COUNT, buffer);
	int result = 0, maxLen = 0;

	for(int i = 0; i < realCount - 1; ++i)
		{
		buffer[i + 1] += buffer[i];
		if(buffer[i + 1] >= COUNT)
			{
			realCount = i;
			break;
			}
		}
	for(int i = realCount; i >= 0; --i)
		{
		int temp = buffer[i];
		if(IsPrime(temp))
			{
			if(i > maxLen)
				{
				maxLen = i;
				result = temp;
				}
			}
		else
			for(int j = 0; j < realCount; ++j)
				{
				if(IsPrime(temp - buffer[j]))
					{
					if(i - j - 1 > maxLen)
						{
						maxLen = i - j - 1;
						result = temp - buffer[j];
						}
					}
				}
		}
	delete []buffer;
	return result;
	}
Beispiel #30
0
int main(int argc, const char * argv[]) {
    unsigned long sum = 0;
    
    for (int i = 2; i < LIMIT; i++) {
        sum += IsPrime(i) != 0 ? i : 0;
    }
    
    printf("Sum is %li\n", sum);

    return 0;
}