Categories
Class 11 Class 12

Consecutive Natural Numbers Program in Java

A positive natural number, for example 27 can be represented as follows:
2 + 3 + 4 + 5 + 6 + 7
8 + 9 + 10
13 + 14
where every row represents a combination of consecutive natural numbers, which add up to 27.

Write a program which inputs a positive natural number N and prints the possible consecutive number combinations, which when added give N.

Test your program for the following data and some random data.

Example 1:
INPUT:
N = 9
OUTPUT:
4 + 5
2 + 3 + 4

Example 2:
INPUT:
N = 15
OUTPUT:
7 + 8
1 + 2 + 3 + 4 + 5
4 + 5 + 6

Example 3:
INPUT:
N = 21
OUTPUT:
10 + 11
1 + 2 + 3 + 4 + 5 + 6
6 + 7 + 8

import java.io.*;
class Consecutive{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        String seq = "";
        for(int i = n - 1; i >= 1; i--){
            int sum = 0;
            seq = "";
            boolean status = false;
            for(int j = i; j >= 1; j--){
                sum += j;
                seq = j + " + " + seq;
                if(sum == n){
                    status = true;
                    break;
                }
            }
            if(status)
                System.out.println(seq.substring(0, seq.lastIndexOf('+')));
        }
    }
}

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.