I want to know the smallest number answering the sum problem *1*2*3*4...*n = k
(*
indicates +
or -
). For example:
- for
k = 0
:+1+2-3 = 0
, so, the smallest answer is3
. - for
k = 4
:-1+2+3 = 4
, so the smallest answer is3
. for
k = 12
:-1+2+3+4+5+6-7 = 12
, so the smallest answer is7
. // 4 = -1+2+3// 5 = +1-2-3+4-5 // 6 = +1+2+3 // 7 = -1+2-3+4+5 // 8 = -1+2+3+4 // 9 = -1-2+3+4+5 // 10 = +1+2+3+4 // 11 = +1-2+3+4+5 // 12 = -1+2+3+4+5+6-7 // 13 = -1+2-3+4+5+6 // 14 = -1+2+3+4+5
Is there any algorithm to do this?
import java.util.Random;
import java.util.Scanner;
public class EX_03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Case = sc.nextInt();
int arr[] = new int[Case];
int sum[] = new int[Case];
int k = 0;
int count = 0;
for (int i = 0; i < Case; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < Case; i++) {
while (true) {
++k;
if(count==0){
sum[i] += k;
count++;}
else{
sum[i] -= k;
}
if(sum[i] == arr[i]) break;
}
}
// 0 = +1+2-3
// 1 = +1
// 2 = +1-2+3
// 3 = +1+2
// 4 = -1+2+3
// 5 = +1-2-3+4-5
// 6 = +1+2+3
// 7 = -1+2-3+4+5
// 8 = -1+2+3+4
// 9 = -1-2+3+4+5
// 10 = +1+2+3+4
// 11 = +1-2+3+4+5
// 12 = -1+2+3+4+5+6-7
// 13 = -1+2-3+4+5+6
// 14 = -1+2+3+4+5
// 15 = 123456
/*
* Random operatorChoice = new Random(); int operator =
* operatorChoice.nextInt(2);
*
* while (k >= 0) { ++k; for (int i = 0; i < Case; i++) { switch
* (operator) { case 0: sum[i] += k; break; case 1: sum[i] -= k; break;
* default: break; } if(sum[i] == arr[i]) break; else continue; } }
*/
for (int i = 0; i < Case; i++) {
System.out.println(k);
}
}
}
Example input:
12 -3646397
Expected output for that input:
7 2701