Solution to
problem number 60 of Project Euler.
Question # 60The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
Solution # 60
/**********************************************************************/
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define max 1000000
int arr[max]={0};
void set_arr();
int is_prime(long int);
int is_conPrime(long int,
long int);
int main()
{
long int i,sum=0,a,b,c,d,e,min=2147483647;
set_arr();
for(a=3;a<10000;a+=2)
if(arr[a])
for(b=3;b<10000;b+=2)
if(arr[b] && is_conPrime(a,b))
for(c=3;c<10000;c+=2)
if(arr[c] &&
is_conPrime(a,c) && is_conPrime(b,c))
for(d=3;d<10000;d+=2)
if(arr[d] &&
is_conPrime(a,d) && is_conPrime(b,d) && is_conPrime(c,d))
for(e=3;e<10000;e+=2)
if(arr[e]
&& is_conPrime(a,e) && is_conPrime(b,e) &&
is_conPrime(c,e) && is_conPrime(d,e))
{
printf("%ld
%ld %ld %ld %ld\nsum = %ld",a,b,c,d,e,(a+b+c+d+e));
exit(1);
}
return 0;
}
void set_arr()
{
int i;
for(i=2;i<max;i++)
if(is_prime(i))
arr[i]=1;
}
int is_prime(long int n)
{
long int i;
if(n==1)
return 0;
if(n==2)
return 1;
if(n%2==0)
return 0;
for(i=3;i*i<=n;i+=2)
if(n%i==0)
return 0;
return 1;
}
int count_digits(long int n)
{
int counter=0;
while(n)
{
counter++;
n/=10;
}
return counter;
}
int is_conPrime(long int
a,long int b)
{
long int num1,num2;
num1=a+b*(long)pow(10,count_digits(a));
num2=b+a*(long)pow(10,count_digits(b));
if(is_prime(num1) && is_prime(num2))
return 1;
return 0;
}
/**********************************************************************/
No comments:
Post a Comment