Search code examples
javascriptpascal

Please help to translate code Pascal to JS?


I have task: On a sheet of paper, a rectangle is drawn along the grid lines. After that, the number of grid nodes located inside, but not on the border of the rectangles, and the number of single grid segments inside the rectangle were counted. Write a program that uses this data to determine the size of a rectangle.

I have this code in Pascal:

var
K,N,i,j:integer;
begin
readln(K,N);
for i:=1 to trunc(sqrt(K)) do
if K mod i = 0 then
begin
if i*(K div i+1)+(K div i)*(i+1)=N then writeln(i+1,' ',K div i+1);
end;
end.

And this my code in JavaScript:

const a = [1000, 2065]

function Sum(K, N) {
  for (i = 1; i < Math.trunc(Math.sqrt(K)); i++) {
    if (K % i === 0 && i * (Math.floor(K / (i) + 1) + Math.floor(K / i) * (i + 1)) === N) {
      break;
    }
  }
  console.log(i + 1, Math.floor(K / (i)) + 1)
}
Sum(a[0], a[1]);

Can you help why my answers in JavaScript are wrong?


Solution

  • Not exactely sure what you're trying to achieve but this javascript code produces the same output (26, 41) as your pascal version does:

    See onlinegdb.com!

    const K = 1000, N = 2065;
    for (let i=1; i<Math.trunc(Math.sqrt(K)); i++)
      if (K % i === 0)
        if (i*(K / i+1)+(K / i)*(i+1) === N)
            console.log(i+1, K / i+1);

    I think you have messed something up with the brackets in Math.floor or something similar.