IQ

Ad SpeedyAds

Sunday, February 7, 2010

java program To find all the sets of consecutive natural numbers which add up to give the given number

import java.io.*;
class combi
{
private static int N;
private static int sum;

public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String S;
System.out.print("Enter an integer: ");
S=br.readLine();
int i=Integer.parseInt(S);
combi A= new combi(i, 0);
A.calc();
}

public combi(int a, int b)
{
N=a;
sum=b;
}


public void calc()throws IOException
{
for(int i=1; i<=N/2;i++)
{
for(int j=i; j<=(N+1)/2; j++)
{
sum+=j;
if(sum==N)
{
for(int a=i; a<=j; a++)
{
System.out.print(a);
System.out.print(a }
System.out.println("");
System.out.println("");
sum=0;
break;
}
}
sum=0;
}

}
}

1 comment:

  1. u see my code is asking for input from the user.. thatswhy it appears so long 2 u..
    as far as the logic is concerened,u hv used the same logic as i have..

    ReplyDelete