Pascal转JavaScript代码调试求助:网格矩形尺寸计算程序结果异常排查
Let's break down why your JavaScript code isn't producing the correct result, and fix it step by step.
Key Issues in Your Code
1. Misplaced Parentheses in the Condition
The biggest mistake is how you translated the Pascal condition to JavaScript. The Pascal code checks if the sum of two products equals N:
i*(K div i+1)+(K div i)*(i+1)=N
But your JavaScript code wraps the entire sum inside a multiplication with i, which changes the logic entirely:
i * (Math.floor(K / (i) + 1) + Math.floor(K / i) * (i + 1)) === N
This computes i * [(j+1) + j*(i+1)] instead of the correct i*(j+1) + j*(i+1) (where j = K/i).
2. Loop Condition Excludes Upper Bound
Your Pascal loop runs i from 1 to trunc(sqrt(K)) (inclusive), but your JavaScript loop uses i < Math.trunc(Math.sqrt(K)), which skips the divisor equal to the square root of K (critical if K is a perfect square).
3. Undeclared Loop Variable
The i variable isn't declared with let inside the loop, which pollutes the global scope and can lead to unexpected behavior.
Corrected JavaScript Code
Here's the fixed version that matches the Pascal logic:
const a = [1000, 2065]; function findRectangleDimensions(K, N) { let width, height; const sqrtK = Math.trunc(Math.sqrt(K)); for (let i = 1; i <= sqrtK; i++) { if (K % i === 0) { const j = Math.floor(K / i); // Correctly calculate the expected N using the Pascal formula const calculatedN = i * (j + 1) + j * (i + 1); if (calculatedN === N) { width = i + 1; height = j + 1; break; // Exit loop once we find the valid pair } } } if (width && height) { console.log(width, height); // Outputs 26 41 for your test case } else { console.log("No valid rectangle dimensions found for the given K and N."); } } findRectangleDimensions(a[0], a[1]);
Why This Works
- Fixed Condition: We now compute the sum of the two products as intended, matching the Pascal logic.
- Inclusive Loop: The loop runs up to and including
sqrt(K), ensuring we check all possible divisors. - Proper Variable Scope:
iis declared withletinside the loop to avoid global scope issues. - Error Handling: We add a check to handle cases where no valid dimensions exist for the input
KandN.
Testing this with your input K=1000 and N=2065 will correctly output 26 41, which is the right result (since (26-1)*(41-1)=25*40=1000 and 25*(40+1)+40*(25+1)=2065).
内容的提问来源于stack exchange,提问作者advanced_one

