I found the code on the Internet but I can not understand what's what.


Task:

Print the squares of natural numbers from 0 to n using "+" and "-"

k:=0; k_square:=0; writeln(k.square); while not (k=n) do begin k:= k+1; k_square:=k_square+k+k-1; writeln(k_square); end; 

Closed due to the fact that the essence of the question is not clear to the participants of Kromster , AK , 0xdb , Viktor Tomilov , user192664 12 Nov '18 at 4:20 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

    2 answers 2

    Recall the fifth grade algebra, namely the square of the sum:

     (a+b)^2 = a^2 + 2ab + b^2 

    In our case, when we calculate the next member of the series, this transforms into an expression:

     (a+1)^2 = a^2 + 2a + 1 

    or, using only pros and cons:

     (a+1)^2 = a^2 + (a+1) + (a+1) - 1 

    This is where your code fits perfectly :)

    • Why (a+1) + (a+1) - 1 ?) This is after all a + a + 1 , only extra 2 operations) - Kir_Antipov
    • one
      @Kir_Antipov Do you have a in this iteration? You have the square of the previous number and (a + 1). Of course, you can save a, but in the problem it is not provided, as I understand it - Viktor Tomilov
    • @Kir_Antipov is written to use minus when calculating, that's what they use - teran

    Starting from 1:

    k_square = 0 + 1 + 1 - 1 (It turns out 1, square 2. 1 Remains in a variable)

    k_square = 1 + 2 + 2 - 1 (It turns out 4, hell 2. 4 Remains in the variable)

    k_square = 4 + 3 + 3 - 1 (It turns out 9, square 3. 9 Remains in the variable)

    And so on. So you can do with any number, the formula is approximately as follows:

     Квадрат числа = (Квадрат предыдущего числа) + (число квадрат которого мы ищем) + (число квадрат которого мы ищем) - 1; 

    One more example:

    42_square = 1681 (square 41) + 42 + 42 - 1 = 1764 = 42 ^ 2

    • But how should I solve this problem when solving this problem? - Ivan Shkurko
    • @ IvanShkurko Honestly - I do not know. In theory, if you sit on a piece of paper with a textbook, you can guess. Logics. - ValeraGrinenko
    • one
      Write a series of squares 0 1 4 9 16 25 and the differences between them 1 3 5 7 9 11 - MBo
    • one
      @ IvanShkurko: no need to guess here. Arithmetic for pyatiklashek. (n + 1)^2 = n^2 + 2n + 1 , which is read as the квадрат каждого следующего числа равняется сумме квадрата предыдущего числа, его удвоенного произведения и единицы . They also gave you the formula: (n+1)^2 = n^2 + 2(n+1) - 1 = n^2 + 2n + 1 , which should not be, because this complication is initial - Kir_Antipov
    • @MBo This is the property of the squares of natural numbers, which I am trying to drive into the heads of my children :) (with varying success). - Igor