我正在嘗試解決這個問題:檢查陣列的元素是否是1的連續和。輸入Q(陣列長度,1≤Q≤10^3),然后輸入基于長度的元素(1≤N[i ]≤10^18)。示例:6=1 2 3 列印是。10=1 2 3 4 列印 是。5=2 3 列印沒有因為它不是來自 1 的連續總和 事情是我的代碼在一個小數字上作業,例如 6、10、15。但我還需要根據條件檢查更大的數字(如 234223743)。我怎樣才能簡化我的代碼?我的代碼:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum =0;
int x=1;
int Q = scanner.nextInt();
int []N=new int [Q];
for (int i = 0 ; i<Q;i ){
N [i]= scanner.nextInt();
while (sum <N[i]){
sum = sum x;
x ;
}
if (sum==N[i]){
System.out.println("YES");
}
else{
System.out.println("NO");
}
sum=0;
x=1;
}
scanner.close();
}
uj5u.com熱心網友回復:
數學在這里有效。您可以使用二次方程解。前 N 個自然數之和為 n*(n 1)/2。所以基本上
? 1 2 3 …. N = S
? (N * (N 1)) / 2 = S
? N * (N 1) = 2 * S
? N2 N – 2 * S = 0
我們知道您的 s,所以只需求解二次方程即可。就像是
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum =0;
int x=1;
int Q = scanner.nextInt();
int []N=new int [Q];
for (int i = 0 ; i<Q;i ){
N [i]= scanner.nextInt();
// Solution of Quadratic Equation
double k = (-1.0 Math.sqrt(1 8 * N[i])) / 2;
// Condition to check if the
// solution is a integer
if (Math.ceil(k) == Math.floor(k))
System.out.println("YES");
else
System.out.println("NO");
}
}
如果您有興趣,此頁面也有二進制搜索解決方案。 https://www.geeksforgeeks.org/find-given-number-sum-first-n-natural-numbers/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478928.html
