Code with Vinay

ISC practical papers › ISC 2006 › Question 1

Consecutive Integers With A Given Sum

ISC 2006 Computer Science Practical, Question 1 · Number programs

The question

A positive natural number, (for e.g. 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.
SAMPLE DATA
INPUT:  N = 9
OUTPUT:
    4 + 5
    2 + 3 + 4
INPUT:  N = 15
OUTPUT:
    7 + 8
    1 + 2 + 3 + 4 + 5
    4 + 5 + 6
INPUT:  N = 21
OUTPUT:
    10 + 11
    1 + 2 + 3 + 4 + 5 + 6
    6 + 7 + 8

Question: ISC 2006 Computer Science Paper 2 (Practical), Question 1, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.

Java solution

ISC2006Q1.java Download GitHub
import java.util.*;
class ConsecutiveIntegers{
    private int N;
    private String output;
    private boolean found;
    public ConsecutiveIntegers(int N){
        this.N = N;
        found=false;
        findSum();
    }
    public void findSum(){
        output="";
        int half=N/2;
        for(int beg=1, end=1, sum=1;beg<=half;){
            if(sum<N){
                end+=1;
                sum+=end;
            }else if(sum>N){
                sum-=beg;
                beg+=1;
            }else if(sum==N){
                output+="\t";
                for( int term = beg; term<=end; term++){
                    output+=term;
                    if(term<end) output+=" + ";
                }
                output+="\n";
                found=true;
                sum-=beg;
                beg+=1;
            }
        }
    }
    public String toString(){
        if(found) return output;
        else return "\tNO SOLUTION EXISTS";
    }
}
class ISC2006Q1{
    public static void main(String[] args) {
        Scanner in = new Scanner( System.in );
        System.out.print("INPUT:\tN = ");
        int N = in.nextInt();
        ConsecutiveIntegers obj = new ConsecutiveIntegers(N);
        System.out.println("OUTPUT:\n"+obj);
        in.close();
    }
}

All these solutions in one free book

Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.

Get the free PDF ₹0 ISC 2027 mock papers