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)
10
55
50
12586269025
Fibonacci numbers are defined by F(1) = F(2) = 1 and F(k) = F(k-1) + F(k-2).
Given n, print F(n).
10
55
50
12586269025
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.
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.
n = int(input())a, b = 1, 1for _ in range(n - 1): a, b = b, a + bprint(a)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);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);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); }}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); }}#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';}#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;}n = Console.ReadLine().ToNumber();a = 1;b = 1;for (i = 1; i < n; i++){ next = a + b; a = b; b = next;}Console.WriteLine(a);