Program opened below. You can scroll through the algorithm, Java code and output.

Represent a Number as Consecutive Positive Integers

Download .java

Question

Accept a positive integer N and display each sequence of two or more consecutive positive integers whose sum is N.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Input N and reject N <= 0. Step 4: Validate the input values and display an error message if they are outside the permitted range. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: For each starting value start from 1 while start*(start+1)/2 <= N, set sum=0. Step 7: Add consecutive integers beginning at start until sum >= N. Step 8: If sum equals N and at least two terms were used, display the sequence. Step 9: Continue with the next start value. Step 10: If no sequence is found, display an appropriate message. Step 11: Stop.
Java
import java.util.*;
class ConsecutiveSum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 1) {
            System.out.println("INVALID INPUT");
            return;
        }
    boolean found = false;
    for (int start = 1; start < n; start++) {
        int sum = 0;
        for (int end = start; sum < n; end++) {
            sum += end;
            if (sum == n && end > start) {
                for (int k = start; k <= end; k++) {
                    System.out.print(k + (k < end ? "+" : ""));
                }
            System.out.println();
            found = true;
            break;
        }
}
}
if (!found) {
    System.out.println("NO CONSECUTIVE SUM FOUND");
}
}
}
Input: 15 Output: 7+8 4+5+6
← Previous Program 69 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.