Share on Google+Share on Google+

Find consecutive numbers whose sum is equal to input number.

Advertisement
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

Advertisements

Advertisement

Posted on: January 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.