I made a simple program - conservative sequence integers with a sum, for example input: 15, the output should be 1, 2, 3, 4, 5
I made this program in c++ and it worked successfully, see below:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num, i, j, k;
int sum = 0;
cout << "Num? ";
cin >> num;
for (i = 1; i <= num/2+1; i++) {
j=i;
while(sum<num) {
sum = sum + j;
j++;}
if (sum==num) {
for (k = i; k < j; k++)
if (!k) {
cout << "Not an exact sum!";
}
else {
cout << " " << k;
}
}
}
cout << endl;
system("pause");
return 0;
}
However, the problem is I'm translating this into java and it didn't work. See the java code below, any suggestions?
import java.util.Scanner;
public class Week2 {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Type an integer:");
int n = keyboard.nextInt();
// write your code here; k is the result of the computation //
int i, j = 0, k;
int sum = 0;
for (i = 1; i <= n/2+1; i++)
j = i;
while(sum < n)
sum = sum + j;
j++;
if (sum == n)
for (k = i; k < j; k++)
// do not modify anything beyond this comment //
if (k == 0)
System.out.println("The number "+n+" is not an exact sum");
else
System.out.println("The number "+n+" is the sum of integers from 1 to "+k);
}
}