Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
JavaScript - Right Pascal pattern with the Fibonacci sequence

I'm trying to create a Pascal triangle using the Fibonacci sequence. I´m looking for this output:

0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8 
0 1 1 2 3 5
0 1 1 2 3
0 1 1 2
0 1 1
0 1
0

This is the code I have written so far. I managed to get the Fibonacci sequence running into a triangle but not the way I want.

function fiboP(n) {
  let string = "";
  let n1 = 0
  let n2 = 1
  for (let i = 1; i <= n; i++) {
    for (let j = 0; j < i; j++) {
      string += n1 + " ";
      next_num = n1 + n2;
      n1 = n2;
      n2 = next_num;
    }
    string += "\n";
  }
  for (let i = 1; i <= n - 1; i++) {
    for (let j = 0; j < n - i; j++) {
      string += n1 + " ";
      next_num = n2 - n1;
      n2 = n1;
      n1 = next_num;
    }
    string += "\n";

  }
  console.log(string)
}


fiboP(5)

Output:
0 
1 1 
2 3 5 
8 13 21 34 
55 89 144 233 377 
610 377 233 144 
89 55 34 
21 13 
8

I would like to understand what I am missing here and if there is a cleaner and simpler way to produce the desired output.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you reset your values when you go to next line, you should be able to generate the output you're looking for

function fiboP(n) {
  let string = "";
  for (let i = 1; i <= n; i++) {
    let n1 = 0
    let n2 = 1
    for (let j = 0; j < i; j++) {
      string += n1 + " ";
      next_num = n1 + n2;
      n1 = n2;
      n2 = next_num;
    }
    string += "\n";
  }
  for (let i = 1; i <= n - 1; i++) {
    let n1 = 0
    let n2 = 1
    for (let j = 0; j < n - i; j++) {
      string += n1 + " ";
      next_num = n2 + n1;
      n2 = n1;
      n1 = next_num;
    }
    string += "\n";

  }
  console.log(string)
}


fiboP(7)

As an improvement i will suggest finding fibonacci sequence once and then just using these values to create this triangle.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda