Improve solution for problem 46
This commit is contained in:
parent
a82d270691
commit
9df4d3fe97
22
C/p046.c
22
C/p046.c
@ -1,3 +1,16 @@
|
|||||||
|
/* It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
|
||||||
|
*
|
||||||
|
* 9 = 7 + 2×1^2
|
||||||
|
* 15 = 7 + 2×2^2
|
||||||
|
* 21 = 3 + 2×3^2
|
||||||
|
* 25 = 7 + 2×3^2
|
||||||
|
* 27 = 19 + 2×2^2
|
||||||
|
* 33 = 31 + 2×1^2
|
||||||
|
*
|
||||||
|
* It turns out that the conjecture was false.
|
||||||
|
*
|
||||||
|
* What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?*/
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
@ -24,6 +37,9 @@ int main(int argc, char **argv)
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* For every odd number, check if it's prime, if it is check
|
||||||
|
* if it satisfies the Goldbach property. Continue until the
|
||||||
|
* first number that doesn't is found.*/
|
||||||
for(i = 3; !found && i < N; i += 2)
|
for(i = 3; !found && i < N; i += 2)
|
||||||
{
|
{
|
||||||
if(!primes[i])
|
if(!primes[i])
|
||||||
@ -53,12 +69,15 @@ int goldbach(int n)
|
|||||||
{
|
{
|
||||||
int i, j, tmp;
|
int i, j, tmp;
|
||||||
|
|
||||||
for(i = 2; i < n; i++)
|
/* Check every prime smaller than n.*/
|
||||||
|
for(i = 3; i < n; i += 2)
|
||||||
{
|
{
|
||||||
if(primes[i])
|
if(primes[i])
|
||||||
{
|
{
|
||||||
j = 1;
|
j = 1;
|
||||||
|
|
||||||
|
/* Check if summing twice a square to the prime number
|
||||||
|
* gives n. Return 1 when succeeding.*/
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
tmp = i + 2 * j * j;
|
tmp = i + 2 * j * j;
|
||||||
@ -73,5 +92,6 @@ int goldbach(int n)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Return 0 if no solution is found.*/
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,7 @@ from projecteuler import sieve
|
|||||||
def goldbach(n):
|
def goldbach(n):
|
||||||
global primes
|
global primes
|
||||||
|
|
||||||
for i in range(2, n):
|
for i in range(3, n, 2):
|
||||||
if primes[i] == 1:
|
if primes[i] == 1:
|
||||||
j = 1
|
j = 1
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user