DEV Community

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

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay