{ }codelper
for loop64-bit integersrecursionP0010

Fibonacci number

Fibonacci numbers are defined by F(1) = F(2) = 1 and F(k) = F(k-1) + F(k-2).
Given n, print F(n).

Input
1 ≤ n ≤ 70
Output
F(n)
Example 1 · stdin
10
stdout
55
Example 2 · stdin
50
stdout
12586269025
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

From F(47) the value exceeds a 32-bit int (about 2.1 billion), so C, C++, Java and C# need long/long long.
JavaScript, TypeScript and Craykon are exact up to 2^53, fine through F(78), and Python has no limit.
Plain recursion is far too slow at n = 70, so a loop keeping only the last two values is best.

Pythonmain.py · 5 lines
n = int(input())a, b = 1, 1for _ in range(n - 1):    a, b = b, a + bprint(a)
JavaScriptmain.js · 4 lines
const n = Number(require("fs").readFileSync(0, "utf8"));let a = 1, b = 1;for (let i = 1; i < n; i++) [a, b] = [b, a + b];console.log(a);
TypeScriptmain.ts · 5 lines
import { readFileSync } from "node:fs";const n: number = Number(readFileSync(0, "utf8"));let a: number = 1, b: number = 1;for (let i = 1; i < n; i++) [a, b] = [b, a + b];console.log(a);
JavaMain.java · 14 lines
import java.util.Scanner; public class Main {    public static void main(String[] args) {        int n = new Scanner(System.in).nextInt();        long a = 1, b = 1;        for (int i = 1; i < n; i++) {            long next = a + b;            a = b;            b = next;        }        System.out.println(a);    }}
C#Main.cs · 15 lines
using System; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        long a = 1, b = 1;        for (int i = 1; i < n; i++)        {            (a, b) = (b, a + b);        }        Console.WriteLine(a);    }}
C++main.cpp · 13 lines
#include <iostream> int main() {    int n;    std::cin >> n;    long long a = 1, b = 1;    for (int i = 1; i < n; i++) {        long long next = a + b;        a = b;        b = next;    }    std::cout << a << '\n';}
Cmain.c · 14 lines
#include <stdio.h> int main(void) {    int n;    scanf("%d", &n);    long long a = 1, b = 1;    for (int i = 1; i < n; i++) {        long long next = a + b;        a = b;        b = next;    }    printf("%lld\n", a);    return 0;}
Craykonmain.cray · 10 lines
n = Console.ReadLine().ToNumber();a = 1;b = 1;for (i = 1; i < n; i++){    next = a + b;    a = b;    b = next;}Console.WriteLine(a);