The Wayback Machine - https://web.archive.org/web/20240708012343/https://www.geeksforgeeks.org/program-for-goldbachs-conjecture-two-primes-with-given-sum/
Open In App

Program for Goldbach’s Conjecture (Two Primes with given Sum)

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Goldbach’s conjecture is one of the oldest and best-known unsolved problems in the number theory of mathematics. Every even integer greater than 2 can be expressed as the sum of two primes.

Examples:  

Input :  n = 44
Output :   3 + 41 (both are primes)

Input :  n = 56
Output :  3 + 53  (both are primes) 

Approach: 1

  1. Find the prime numbers using Sieve of Sundaram
  2. Check if the entered number is an even number greater than 2 or not, if no return.
  3. If yes, then one by one subtract a prime from N and then check if the difference is also a prime. If yes, then express it as a sum.

Below is the implementation of the above approach: 

C++




// C++ program to implement Goldbach's conjecture
#include<bits/stdc++.h>
using namespace std;
const int MAX = 10000;
  
// Array to store all prime less than and equal to 10^6
vector <int> primes;
  
// Utility function for Sieve of Sundaram
void sieveSundaram()
{
    // In general Sieve of Sundaram, produces primes smaller
    // than (2*x + 2) for a number given number x. Since
    // we want primes smaller than MAX, we reduce MAX to half
    // This array is used to separate numbers of the form
    // i + j + 2*i*j from others where 1 <= i <= j
    bool marked[MAX/2 + 100] = {0};
  
    // Main logic of Sundaram. Mark all numbers which
    // do not generate prime number by doing 2*i+1
    for (int i=1; i<=(sqrt(MAX)-1)/2; i++)
        for (int j=(i*(i+1))<<1; j<=MAX/2; j=j+2*i+1)
            marked[j] = true;
  
    // Since 2 is a prime number
    primes.push_back(2);
  
    // Print other primes. Remaining primes are of the
    // form 2*i + 1 such that marked[i] is false.
    for (int i=1; i<=MAX/2; i++)
        if (marked[i] == false)
            primes.push_back(2*i + 1);
}
  
// Function to perform Goldbach's conjecture
void findPrimes(int n)
{
    // Return if number is not even or less than 3
    if (n<=2 || n%2 != 0)
    {
        cout << "Invalid Input \n";
        return;
    }
  
    // Check only upto half of number
    for (int i=0 ; primes[i] <= n/2; i++)
    {
        // find difference by subtracting current prime from n
        int diff = n - primes[i];
  
        // Search if the difference is also a prime number
        if (binary_search(primes.begin(), primes.end(), diff))
        {
            // Express as a sum of primes
            cout << primes[i] << " + " << diff << " = "
                 << n << endl;
            return;
        }
    }
}
  
// Driver code
int main()
{
    // Finding all prime numbers before limit
    sieveSundaram();
  
    // Express number as a sum of two primes
    findPrimes(4);
    findPrimes(38);
    findPrimes(100);
  
    return 0;
}


Java




// Java program to implement Goldbach's conjecture
import java.util.*;
  
class GFG
{
      
static int MAX = 10000;
  
// Array to store all prime less 
// than and equal to 10^6
static ArrayList<Integer> primes = new ArrayList<Integer>();
  
// Utility function for Sieve of Sundaram
static void sieveSundaram()
{
    // In general Sieve of Sundaram, produces 
    // primes smaller than (2*x + 2) for 
    // a number given number x. Since
    // we want primes smaller than MAX,
    // we reduce MAX to half This array is 
    // used to separate numbers of the form
    // i + j + 2*i*j from others where 1 <= i <= j
    boolean[] marked = new boolean[MAX / 2 + 100];
  
    // Main logic of Sundaram. Mark all numbers which
    // do not generate prime number by doing 2*i+1
    for (int i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++)
        for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1)
            marked[j] = true;
  
    // Since 2 is a prime number
    primes.add(2);
  
    // Print other primes. Remaining primes are of the
    // form 2*i + 1 such that marked[i] is false.
    for (int i = 1; i <= MAX / 2; i++)
        if (marked[i] == false)
            primes.add(2 * i + 1);
}
  
// Function to perform Goldbach's conjecture
static void findPrimes(int n)
{
    // Return if number is not even or less than 3
    if (n <= 2 || n % 2 != 0)
    {
        System.out.println("Invalid Input ");
        return;
    }
  
    // Check only upto half of number
    for (int i = 0 ; primes.get(i) <= n / 2; i++)
    {
        // find difference by subtracting 
        // current prime from n
        int diff = n - primes.get(i);
  
        // Search if the difference is 
        // also a prime number
        if (primes.contains(diff))
        {
            // Express as a sum of primes
            System.out.println(primes.get(i) + 
                        " + " + diff + " = " + n);
            return;
        }
    }
}
  
// Driver code
public static void main (String[] args) 
{
    // Finding all prime numbers before limit
    sieveSundaram();
  
    // Express number as a sum of two primes
    findPrimes(4);
    findPrimes(38);
    findPrimes(100);
}
}
  
// This code is contributed by mits


Python3




# Python3 program to implement Goldbach's 
# conjecture
import math
MAX = 10000;
  
# Array to store all prime less 
# than and equal to 10^6
primes = [];
  
# Utility function for Sieve of Sundaram
def sieveSundaram():
      
    # In general Sieve of Sundaram, produces 
    # primes smaller than (2*x + 2) for a 
    # number given number x. Since we want
    # primes smaller than MAX, we reduce 
    # MAX to half. This array is used to 
    # separate numbers of the form i + j + 2*i*j 
    # from others where 1 <= i <= j
    marked = [False] * (int(MAX / 2) + 100);
  
    # Main logic of Sundaram. Mark all 
    # numbers which do not generate prime
    # number by doing 2*i+1
    for i in range(1, int((math.sqrt(MAX) - 1) / 2) + 1):
        for j in range((i * (i + 1)) << 1, 
                        int(MAX / 2) + 1, 2 * i + 1):
            marked[j] = True;
  
    # Since 2 is a prime number
    primes.append(2);
  
    # Print other primes. Remaining primes 
    # are of the form 2*i + 1 such that 
    # marked[i] is false.
    for i in range(1, int(MAX / 2) + 1):
        if (marked[i] == False):
            primes.append(2 * i + 1);
  
# Function to perform Goldbach's conjecture
def findPrimes(n):
      
    # Return if number is not even 
    # or less than 3
    if (n <= 2 or n % 2 != 0):
        print("Invalid Input");
        return;
  
    # Check only upto half of number
    i = 0;
    while (primes[i] <= n // 2):
          
        # find difference by subtracting 
        # current prime from n
        diff = n - primes[i];
  
        # Search if the difference is also
        # a prime number
        if diff in primes:
              
            # Express as a sum of primes
            print(primes[i], "+", diff, "=", n);
            return;
        i += 1;
  
# Driver code
  
# Finding all prime numbers before limit
sieveSundaram();
  
# Express number as a sum of two primes
findPrimes(4);
findPrimes(38);
findPrimes(100);
  
# This code is contributed
# by chandan_jnu


C#




// C# program to implement Goldbach's conjecture
using System;
using System.Collections.Generic;
  
class GFG
{
      
static int MAX = 10000;
  
// Array to store all prime less 
// than and equal to 10^6
static List<int> primes = new List<int>();
  
// Utility function for Sieve of Sundaram
static void sieveSundaram()
{
    // In general Sieve of Sundaram, produces 
    // primes smaller than (2*x + 2) for 
    // a number given number x. Since
    // we want primes smaller than MAX,
    // we reduce MAX to half This array is 
    // used to separate numbers of the form
    // i + j + 2*i*j from others where 1 <= i <= j
    Boolean[] marked = new Boolean[MAX / 2 + 100];
  
    // Main logic of Sundaram. Mark all numbers which
    // do not generate prime number by doing 2*i+1
    for (int i = 1; i <= (Math.Sqrt(MAX) - 1) / 2; i++)
        for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1)
            marked[j] = true;
  
    // Since 2 is a prime number
    primes.Add(2);
  
    // Print other primes. Remaining primes are of the
    // form 2*i + 1 such that marked[i] is false.
    for (int i = 1; i <= MAX / 2; i++)
        if (marked[i] == false)
            primes.Add(2 * i + 1);
}
  
// Function to perform Goldbach's conjecture
static void findPrimes(int n)
{
    // Return if number is not even or less than 3
    if (n <= 2 || n % 2 != 0)
    {
        Console.WriteLine("Invalid Input ");
        return;
    }
  
    // Check only upto half of number
    for (int i = 0 ; primes[i] <= n / 2; i++)
    {
        // find difference by subtracting 
        // current prime from n
        int diff = n - primes[i];
  
        // Search if the difference is 
        // also a prime number
        if (primes.Contains(diff))
        {
            // Express as a sum of primes
            Console.WriteLine(primes[i] + 
                        " + " + diff + " = " + n);
            return;
        }
    }
}
  
// Driver code
public static void Main (String[] args) 
{
    // Finding all prime numbers before limit
    sieveSundaram();
  
    // Express number as a sum of two primes
    findPrimes(4);
    findPrimes(38);
    findPrimes(100);
}
}
  
/* This code contributed by PrinciRaj1992 */


PHP




<?php
// PHP program to implement Goldbach's 
// conjecture
$MAX = 10000;
  
// Array to store all prime less than
// and equal to 10^6
$primes = array();
  
// Utility function for Sieve of Sundaram
function sieveSundaram()
{
    global $MAX, $primes;
      
    // In general Sieve of Sundaram, produces 
    // primes smaller than (2*x + 2) for a 
    // number given number x. Since we want
    // primes smaller than MAX, we reduce 
    // MAX to half. This array is used to 
    // separate numbers of the form i + j + 2*i*j 
    // from others where 1 <= i <= j
    $marked = array_fill(0, (int)($MAX / 2) + 
                                100, false);
  
    // Main logic of Sundaram. Mark all 
    // numbers which do not generate prime
    // number by doing 2*i+1
    for ($i = 1; $i <= (sqrt($MAX) - 1) / 2; $i++)
        for ($j = ($i * ($i + 1)) << 1; 
             $j <= $MAX / 2; $j = $j + 2 * $i + 1)
            $marked[$j] = true;
  
    // Since 2 is a prime number
    array_push($primes, 2);
  
    // Print other primes. Remaining primes 
    // are of the form 2*i + 1 such that 
    // marked[i] is false.
    for ($i = 1; $i <= $MAX / 2; $i++)
        if ($marked[$i] == false)
            array_push($primes, 2 * $i + 1);
}
  
// Function to perform Goldbach's conjecture
function findPrimes($n)
{
    global $MAX, $primes;
      
    // Return if number is not even 
    // or less than 3
    if ($n <= 2 || $n % 2 != 0)
    {
        print("Invalid Input \n");
        return;
    }
  
    // Check only upto half of number
    for ($i = 0; $primes[$i] <= $n / 2; $i++)
    {
        // find difference by subtracting 
        // current prime from n
        $diff = $n - $primes[$i];
  
        // Search if the difference is also a 
        // prime number
        if (in_array($diff, $primes))
        {
            // Express as a sum of primes
            print($primes[$i] . " + " .
                  $diff . " = " . $n . "\n");
            return;
        }
    }
}
  
// Driver code
  
// Finding all prime numbers before limit
sieveSundaram();
  
// Express number as a sum of two primes
findPrimes(4);
findPrimes(38);
findPrimes(100);
  
// This code is contributed by chandan_jnu
?>


Javascript




<script>
// Javascript program to implement Goldbach's 
// conjecture
let MAX = 10000;
  
// Array to store all prime less than
// and equal to 10^6
let primes = new Array();
  
// Utility function for Sieve of Sundaram
function sieveSundaram()
{   
    // In general Sieve of Sundaram, produces 
    // primes smaller than (2*x + 2) for a 
    // number given number x. Since we want
    // primes smaller than MAX, we reduce 
    // MAX to half. This array is used to 
    // separate numbers of the form i + j + 2*i*j 
    // from others where 1 <= i <= j
    let marked = new Array(parseInt(MAX / 2) + 100).fill(false);
  
    // Main logic of Sundaram. Mark all 
    // numbers which do not generate prime
    // number by doing 2*i+1
    for (let i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++)
          for (let j = (i * (i + 1)) << 1; 
            j <= MAX / 2; j = j + 2 * i + 1)
            marked[j] = true;
  
    // Since 2 is a prime number
    primes.push(2);
  
    // Print other primes. Remaining primes 
    // are of the form 2*i + 1 such that 
    // marked[i] is false.
    for (let i = 1; i <= MAX / 2; i++)
        if (marked[i] == false)
            primes.push(2 * i + 1);
}
  
// Function to perform Goldbach's conjecture
function findPrimes(n)
{
    // Return if number is not even 
    // or less than 3
    if (n <= 2 || n % 2 != 0)
    {
        document.write("Invalid Input <br>");
        return;
    }
  
    // Check only upto half of number
    for (let i = 0; primes[i] <= n / 2; i++)
    {
        // find difference by subtracting 
        // current prime from n
        let diff = n - primes[i];
  
        // Search if the difference is also a 
        // prime number
        if (primes.includes(diff))
        {
            // Express as a sum of primes
            document.write(primes[i] + " + " + diff + " = " + n + "<br>");
            return;
        }
    }
}
  
// Driver code
  
// Finding all prime numbers before limit
sieveSundaram();
  
// Express number as a sum of two primes
findPrimes(4);
findPrimes(38);
findPrimes(100);
  
// This code is contributed by gfgking
</script>


Output

2 + 2 = 4
7 + 31 = 38
3 + 97 = 100

Time Complexity: O(n log n)
Auxiliary Space: O(MAX)

A Goldbach number is a positive integer that can be expressed as the sum of two odd primes. Since four is the only even number greater than two that requires the even prime 2 in order to be written as the sum of two primes, another form of the statement of Goldbach’s conjecture is that all even integers greater than 4 are Goldbach numbers.
 

 



Previous Article
Next Article

Similar Reads

Goldbach's Weak Conjecture for Odd numbers
Given an odd number N, the task is to find if the number can be represented as the sum of 3 prime numbers.Examples: Input: N = 7 Output: Yes Explanation: 2 + 2 + 3 = 7 Input: N = 17 Output: Yes Explanation: 2 + 2 + 13 = 17 Approach: In number theory, Goldbach's weak conjecture, also known as the odd Goldbach conjecture, the ternary Goldbach problem
3 min read
Count primes that can be expressed as sum of two consecutive primes and 1
Given a number N. The task is to count the number of prime numbers from 2 to N that can be expressed as a sum of two consecutive primes and 1.Examples: Input: N = 27 Output: 2 13 = 5 + 7 + 1 and 19 = 7 + 11 + 1 are the required prime numbers.Input: N = 34 Output: 3 13 = 5 + 7 + 1, 19 = 7 + 11 + 1 and 31 = 13 + 17 + 1. Approach: An efficient approac
9 min read
Count of primes below N which can be expressed as the sum of two primes
Given an integer N, the task is to find the count of all the primes below N which can be expressed as the sum of two primes.Examples: Input: N = 6 Output: 1 5 is the only such prime below 6. 2 + 3 = 5.Input: N = 11 Output: 2 Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach: Create an array prime[] wher
11 min read
Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range
Given two integers X and Y, the task is to perform the following operations: Find all prime numbers in the range [X, Y].Generate all numbers possible by combining every pair of primes in the given range.Find the prime numbers among all the possible numbers generated above. Calculate the count of primes among them, say N.Print the Nth term of a Fibo
13 min read
Length of largest sub-array having primes strictly greater than non-primes
Given an array 'arr' of length 'n'. The task is to find the largest contiguous sub-array having the count of prime numbers strictly greater than the count of non-prime numbers. Examples: Input: arr[] = {4, 7, 4, 7, 11, 5, 4, 4, 4, 5} Output: 9 Input: arr[] = { 1, 9, 3, 4, 5, 6, 7, 8 } Output: 5 Approach: To find the largest subarray in which count
8 min read
Program to implement Collatz Conjecture
Given a positive integer n, the task is to find whether this number reaches 1 after performing the following two operations:- If n is even, then n = n/2.If n is odd, then n = 3*n + 1.Repeat the above steps, until it becomes 1.For example, for n = 12, we get the sequence 12, 6, 3, 10, 5, 16, 8, 4, 2, 1. Examples: Input : n = 4Output : YesInput : n =
7 min read
Lemoine's Conjecture
Any odd integer greater than 5 can be expressed as a sum of an odd prime (all primes other than 2 are odd) and an even semiprime. A semiprime number is a product of two prime numbers. This is called Lemoine's conjecture. Examples : 7 = 3 + (2 × 2), where 3 is a prime number (other than 2) and 4 (= 2 × 2) is a semiprime number.11 = 5 + (2 × 3) where
8 min read
Ramanujan–Nagell Conjecture
The Ramanujan-Nagell equation is an equation between a number (say, x) which is squared and another number (say, z) such that z = [Tex]2^n - 7[/Tex]. Here, n can be any positive natural number which satisfies the equation. It is an example of an exponential Diophantine equation, which is an equation that can have only integral solutions with one of
1 min read
Legendre's Conjecture
It says that there is always one prime number between any two consecutive natural number's(n = 1, 2, 3, 4, 5, ...) square. This is called Legendre's Conjecture. Conjecture: A conjecture is a proposition or conclusion based upon incomplete information to which no proof has been found i.e it has not been proved or disproved. Mathematically, there is
5 min read
Triangle of numbers arising from Gilbreath's conjecture
The task is to find the triangle of numbers arising from Gilbreath's conjecture. Gilbreath's conjecture: It is observed that given a sequence of prime numbers, a sequence can be formed by the absolute difference between the ith and (i+1)th term of the given sequence and the given process can be repeated to form a triangle of numbers. This numbers w
11 min read
three90RightbarBannerImg