Code not working as expected to display Gauss Sum

Asked

Viewed 2,403 times

-2

I need to display the Gauss Sum (100+1=101 , 99+2 =101...). For this, I made the following code:

var contador = 1
var subtracao = 0
var total
var numeroMaximo = 10

// no caso o numeroMaximo é o ultimo número inteiro para fazer a soma de gauss 
// usei o sistema de repetição

for (contador <= numeroMaximo / 2; contador++; subtracao++) {
  console.log(total = contador + (numeroMaximo - subtracao));
}

Doing a table test, I have:

// Cada linha é uma iteração do `for`
( 1 <= 5 ; ...) { total = 1 + (10-0) } = 11
( 2 <= 5 ;...) { total = 2 + (10-1) } = 11
...
(5 <= 5 ;...) { total = 5 + (10-4) } = 11

I mean, it would work: 1+10 ; 2+9 ; 3+8 ; 4+7 ; 5+6 (as the exercise asks)

The problem is that in the execution of the code

  1. Is in infinite loop

  2. Every result is = 12

I’m very lost, because on paper it seems to work.

1 answer

2

Well, there are some problems in your code. But first of all, I recommend using ; at the end of the lines, see Whether or not to use semicolons at the end of Javascript lines? for more details.

The variable total and the exhibition with console.log

Next point, you don’t need the variable total, because you just want to display the result on console.log. And yet on that, you’re performing an assignment total = ... within the console.log, That doesn’t make sense for two reasons:

  1. The console.log serves for you to display a log message, for example console.log('Oi'). Behold What is console.log?
  2. If you want to store the value in total, do it before the console. But with this you will not be able to display the Gauss Sum as you wish:

var total = 1 + 10;
console.log(total); // exibirá 11, não 1 + 10

Keeping this in mind, let’s move the code. For now it stays that way (still not working):

// removemos o `var total`
var contador = 1;  // colocamos ;
var subtracao = 0;
var numeroMaximo = 10;

for (contador <= numeroMaximo / 2; contador++; subtracao++) {
  // removemos a atribuição `total =`
  // além disso, tratamos o "+" como texto porque não queremos realizar a operação
  // apenas exibí-la
  console.log(contador + ' + ' + (numeroMaximo - subtracao));
}

The loop of repetition for

The syntax of noose for is the following:

for ([inicialização]; [condição]; [expressão final])
   declaração
  • [inicialização] - Usually used to start the variable counter. As we have already started before the for, we will not use this for now (at the end of the answer I show an alternative using this).

  • [condição] - An expression to be evaluated before each loop iteration to decide whether declaração will be executed or not. In this case it is the contador <= numeroMaximo / 2;.

  • [expressão final] - An expression that will be validated at the end of each loop iteration. Here we use to increment (or decrement) a loop control variable. In this case we have two expressions: contador++ and subtracao++. To use more than one expression as [expressão final], beat separate them by ,.

  • declaração - Is the code that will be executed in each loop iteration.

So we have corrected, we have:

var contador = 1;
var subtracao = 0;
var numeroMaximo = 10;

// Note que não temos a inicialização e que separamos a expressão final por vírgula
for (; contador <= numeroMaximo / 2; contador++, subtracao++) {
  console.log(contador + ' + ' + (numeroMaximo - subtracao));
}

There, now we have the expected result: the Gauss Sum.

Extras

As I said in the middle of the answer, we will make use of the for. Like contador and subtracao are used only in the for, do not need to be declared outside it. And as we will use two expressions, we separate by ,:

var numeroMaximo = 10;

for (var contador = 1, subtracao = 0; contador <= numeroMaximo / 2; contador++, subtracao++) {
  console.log(contador + ' + ' + (numeroMaximo - subtracao));
}

It continues to work as expected, but still has a detail. We can make use of strings template to display the text, replacing contador + ' + ' + (numeroMaximo - subtracao)), getting the same result but in a different way.

For this, just the string is between low accents ` and what you want to interpret as expression starting with a siphon $ and between keys {}: ${expressão}. See below how it looks:

var numeroMaximo = 10;

for (var contador = 1, subtracao = 0; contador <= numeroMaximo / 2; contador++, subtracao++) {
  console.log(`${contador} + ${numeroMaximo - subtracao}`);
}

Use strings template it’s not better or worse, it’s just another option :)

One last detail is that within the for, as the [condição] is evaluated with each loop repetition, it means that we are always doing the calculation numeroMaximo / 2. Of course this is a simple calculation and will not cause problems, but it is good to know it. We can improve by doing it as follows:

var numeroMaximo = 10;
var limite = numeroMaximo / 2;  // Realizamos o cálculo uma única vez

for (var contador = 1, subtracao = 0; contador <= limite; contador++, subtracao++) {
  console.log(`${contador} + ${numeroMaximo - subtracao}`);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.