Wednesday 11 February 2015

Goldbach's conjecture


Goldbach's Conjecture

 

Problem

Goldbach's conjecture : Every even integer greater than 2 can be expressed as the sum of two primes.
Write a function which takes a number as input, verify if is an even number greater than 2 and also print atleast one pair of prime numbers.

Approach

1) Assume the two numbers are equal to half of the given number.
2) Choose two numbers as half of numbers.
3) increment first by one and decrement second by 1.
4) if the current pair is prime no print it.
5) Else start from step 3 again.

Solution

#include<stdio.h>

int isPrime(int no) {
 int i;
 if (no <= 1) return 0; // 0 and 1 are not prime.
 for (i=2; i*i <= no; i++) {
     if(no % i == 0) return 0;
 }
 return 1;
}

int main()
{
 int a, b, c, i;
 printf("Enter the even no to find out two prime no whose sum is no - ");
 scanf("%d", &a);
 if (a%2 != 0) {
    printf("Please enter even no only\n");
    return 0;
 }
 b = a/2-1;
 c = a/2+1;
 while (1) {
   if (isPrime(b) && isPrime(c)) {
        printf("b %d and c %d are the primes you were looking for.\n", b, c);
        break;
   }
   else {
        b--;
        c++;
   }
 }

}


No comments:

Post a Comment