Wednesday, 30 October 2013

PROJECT EULER SOLUTION # 146

Solution to problem number 146 of Project Euler.
Question # 146

The smallest positive integer n for which the numbers n2+1, n2+3, n2+7, n2+9, n2+13, and n2+27 are consecutive primes is 10. The sum of all such integers n below one-million is 1242490.
What is the sum of all such integers n below 150 million?

Solution # 146
/*******************************************************************************/
#include<stdio.h>

int is_prime(long long int);
long long int next_prime(long long int);
int fun(long long int);
int main()
{
      long long int i,sum=0;
      for(i=2;i<150000000;i+=2)
      {
            //printf("i = %lld  sum = %lld\n",i,sum);
            if(fun(i))
            {
                  sum+=i;
                  printf("sum = %lld\t\ti = %lld\n",sum,i);
            }

      }

      printf("sum = %lld\n",sum);

      return 0;
}

int is_prime(long long int n)
{
      long long int i;
      if(n%2==0)
            return 0;
      for(i=3;i*i<=n;i+=2)
            if(n%i==0)
                  return 0;
      return 1;
}

long long int next_prime(long long int n)
{
      long long int i;
      for(i=n+2;;i+=2)
      {
            if(is_prime(i))
                  return i;
      }
      return 0;
}

int fun(long long int n)
{
      if(primecheck(n))
            if(next_prime(n*n+1)==n*n+3 && next_prime(n*n+3)==n*n+7 && next_prime(n*n+7)==n*n+9 && next_prime(n*n+9)==n*n+13 && next_prime(n*n+13)==n*n+27)
                  return 1;

      return 0;
}

int primecheck(long long int n)
{
      long long int i;
      if((n*n+1)%2==0)
            return 0;
      for(i=3;i*i<=(n*n+27);i+=2)
      {
            if((n*n+1)%i==0)
                  return 0;
            if((n*n+3)%i==0)
                  return 0;
            if((n*n+7)%i==0)
                        return 0;
                if((n*n+9)%i==0)
                        return 0;
            if((n*n+13)%i==0)
                        return 0;
                if((n*n+27)%i==0)
                        return 0;
      }
      return 1;
}
/*******************************************************************************/

No comments:

Post a Comment