DEV Community

Cover image for Fibonacci Sequence in(JS and Golang)
Neeraj Kumar
Neeraj Kumar

Posted on

Fibonacci Sequence in(JS and Golang)

The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Enter fullscreen mode Exit fullscreen mode

Fibonacci number using the following formula:

Fibonacci(n)=Fibonacci(n-1)+Fibonacci(n-2)

Fibonacci Series Up to n Terms(JS)

const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;

console.log('Fibonacci Series:');

for (let i = 1; i <= number; i++) {
    console.log(n1);
    nextTerm = n1 + n2;
    n1 = n2;
    n2 = nextTerm;
}
Enter fullscreen mode Exit fullscreen mode

Fibonacci Series Up to n Terms(Golang)

package main

import (
  "fmt"
)

func Fibonacci(n int) {

  var n3, n1, n2 int = 0, 0, 1

  for i := 1; i <= n; i++ {

    fmt.Println(n1)

    n3 = n1 + n2

    n1 = n2

    n2 = n3

  }
}

func main() {

    Fibonacci(10)

  }


Enter fullscreen mode Exit fullscreen mode

Using Recursion(Golang)

package main

import (
  "fmt"
)

func Fibonacci(n int) int {

  if n <= 1 {

    return n

  }

  return Fibonacci(n-1) + Fibonacci(n-2)

}

func main() {

  for i := 1; i <= 10; i = i + 1{

    fmt.Println(Fibonacci(i))

  }

}
Enter fullscreen mode Exit fullscreen mode

Fibonacci Sequence Up to a Certain Number(JS)

const number = parseInt(prompt('Enter a positive number: '));
let n1 = 0, n2 = 1, nextTerm;

console.log('Fibonacci Series:');
console.log(n1); // print 0
console.log(n2); // print 1

nextTerm = n1 + n2;

while (nextTerm <= number) {

    // print the next term
    console.log(nextTerm);

    n1 = n2;
    n2 = nextTerm;
    nextTerm = n1 + n2;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)