Home Tutorial Java Core Find consecutive numbers whose sum is equal to input number.

 
 

Find consecutive numbers whose sum is equal to input number.
Posted on: January 15, 2010 at 12:00 AM
In this section, you will learn how to display the consecutive natural numbers whose sum is equal to the input number.

Find consecutive numbers whose sum is equal to input number.

In this section, you will learn how to display the consecutive natural numbers whose sum is equal to the input number. For this purpose, the user is allowed to input a positive natural number. The code then takes the number N given by the user and finds all possible combination of consecutive naturalnumbers which add up to give the N. We have used StringBuffer class to hold the combination of consecutive natural numbers which sum up to given number.

Here is the code:

import java.util.*;

public class ConsecutiveNum{
	public static void main(String[] args) {
		int num;
		Scanner input = new Scanner(System.in);
		System.out.println("Enter a number");
		num = input.nextInt();
		for (int i = 1; i < num; i++) {
			StringBuffer sb = new StringBuffer();
			int sum = i;
			sb.append(i).append(" ");
			for (int j = i + 1; sum < num; j++) {
				sb.append(j).append(" ");
				sum = sum + j;
				if (sum == num) {
				System.out.println(sb.toString());
				}
			}
		}
	}
}

Output:

Enter a number
15
1 2 3 4 5
4 5 6
7 8

Related Tags for Find consecutive numbers whose sum is equal to input number.:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.