Skip to content

Instantly share code, notes, and snippets.

@HelixSpiral
Created February 7, 2013 19:55
Show Gist options
  • Save HelixSpiral/4733654 to your computer and use it in GitHub Desktop.
Save HelixSpiral/4733654 to your computer and use it in GitHub Desktop.
Challenge: If a number, 'X' is prime then 2^X-1 should also be prime, find at which prime this fails to be true. This uses the trial and error method of finding prime numbers.
#include <iostream>
#include <cmath>
#include "Prime.h"
int main()
{
int x;
bool Failure = false;
for (x = 1; Failure != true; ++x)
{
if (IsPrime(x))
{
std::cout << "Prime: " << x << std::endl;
if (!IsPrime(pow(2,x)-1))
{
std::cout << "Fails on " << x << std::endl;
Failure = true;
}
}
}
return 0;
}
#ifndef PRIME_H_24122011
#define PRIME_H_24122011
/* Declare function */
int IsPrime(int number)
{
/* 1 and 2 are both prime, so this catches them */
if(number < 3 && number > 0)
return 1;
/* Any even number other than 2 is not prime. */
if(number % 2 == 0)
return 0;
/* Declare variables */
int x;
int limit = number; // This will make the search faster
/* Loop while x < limit. */
for(x = 3; x < limit; x += 2)
{
/* If this hits the number isn't prime. */
if(number % x == 0)
return 0;
/* Making the limit number/x instead of just number
we gain a noticable speed increase */
limit = number / x;
}
/* Number is prime. */
return 1;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment