Proxy > Gmail Facebook Yahoo!

18. Goldbach's Conjecture. Goldbach's Conjecture is that any even number is the sum of two primes. Write a program to test Goldbach's Conjecture over a range of numbers.



import java.util.*;

public class Goldbach
{
  public static void main(String [] args)
  {
    Scanner scan=new Scanner(System.in);
   
    System.out.println("Enter Ending Range:");
    int endRange=scan.nextInt();
   
    System.out.println("Goldbach's Conjecture to Range=:");
    for(int num=4;num<=endRange;num=num+2)
    {
      int firstPrime=2;
      int secondPrime=0;
      while(true)
      {
        secondPrime=num-firstPrime;
        if(!isPrime(secondPrime))
        {
          firstPrime=getNextPrime(firstPrime);
        }
        if(num==(firstPrime+secondPrime)&&isPrime(secondPrime)&&isPrime(firstPrime))
        {
          System.out.println(num+"\t=  "+firstPrime+" + "+secondPrime);
          break;
        }
      }
     
    }
  }
  public static int getNextPrime(int num)
  {
    for(int i=num+1;;i++)
    {
      for(int j=2;j<=i;j++)
      {
        if(i%j!=0)
        {
          return i;
        }
      }
    }
  }
  public static boolean isPrime(int num)
  {
    for(int i=2;i<num;i++)
    {
      if(num%i==0)
      {
        return false;
      }
    }
    return true;
  }
}


Responses

0 Respones to "18. Goldbach's Conjecture. Goldbach's Conjecture is that any even number is the sum of two primes. Write a program to test Goldbach's Conjecture over a range of numbers."


Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar