the following code is to print the nearest twin primes to a number.for eg if the input is 20...the output should be 17 and 19
logic to my code is that it checks for twin primes within the range of a given number and then adds the twin primes.....the twin primes with the largest sum are printed and thus are the nearest primes
but there is some logical error in the program
if i input 20 the output is 132435 and continues till 21...pls help

class nearesttwinprime
{
public void main(int num)
{
int i,j,a,k,b,sum=0,max=0;
for(i=1;i<=num;i++)
{
j=i;
k=i+2;
a=prime(j);
b=prime(k);
if(a==1&&b==1)
{
sum=j+k;
if(max<sum)
sum=max;
}

System.out.print(j);
System.out.print(k);
}}
public int prime(int newnum)
{
int l,c=0;
for(l=1;l<=newnum;l++)
{
if(newnum%l==0)
{
c++;
}
}
if(c==2)
return 1;
else
return 0;
}
}

Recommended Answers

All 2 Replies

I don't see any debugging println statements that would tell you how each variable changes and how the execution flow goes.
If you understand your algorithm and can see when your code is not following that algorithm by looking at how the values of variables change, then the output from the printlns should show you what is happening.

for(i=1;i<=num;i++)

If you want to check nearest prime numbers , then why checking it from i=1 onwards.
Checking from reverse manner i.e (i=num-1) whould be a better approach.

Anyway...here's the solution..

import java.io.*;
class Twin 
{
	public static void main(String[] args) throws Exception
	{    
            int twin[]=new int[2],count=0,k=0;
      System.out.println("Enter the range :");
        
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		int range=Integer.parseInt(br.readLine().trim());
		for(int i=range-1;i>=1;i--)
		{
			 for(int j=2;j<i;j++) 
			{
				 if(i%j==0){count++;break;}
             }
			 
            if(count==0)twin[k++]=i;
              count=0;
			  if(k==2)break;
		}
		
		System.out.println("The twin primes are "+ twin[0] +" and " +twin[1]);
         System.out.println("sum is "+(twin[0]+twin[1]));
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.