Program opened below. You can scroll through the algorithm, Java code and output.
Program 69
Represent a Number as Consecutive Positive Integers
Question
Accept a positive integer N and display each sequence of two or more consecutive positive integers whose sum is N.
Algorithm
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 program
Javaimport 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");
}
}
}Sample output
Input: 15
Output:
7+8
4+5+6