フィボナッチ数列を印刷するJavaScriptプログラム(例付き)

Javascript

フィボナッチ数列は次のように記述されます。

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

フィボナッチ数列は、最初の2つの項が次の整数列です。 0 そして 1。 その後、次の項は前の2つの項の合計として定義されます。


例1:最大n項のフィボナッチ数列

// program to generate fibonacci series up to n terms

// take input from the user
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 the number of terms: 4
Fibonacci Series:
0
1
1
2

上記のプログラムでは、ユーザーはフィボナッチ数列に必要な用語の数を入力するように求められます。

ザ・ for ループは、ユーザーが入力した数まで繰り返されます。

0 最初に印刷されます。 次に、各反復で、第2項の値が変数に格納されます n1 前の2つの項の合計が変数に格納されます n2


例2:特定の数までのフィボナッチ数列

// program to generate fibonacci series up to a certain number

// take input from the user
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 a positive number: 5
Fibonacci Series:
0
1
1
2
3
5

上記の例では、ユーザーはフィボナッチ数列を印刷する番号を入力するように求められます。

最初の2つの用語 0 そして 1 事前に表示されます。 次に、 while ループは、ユーザーが入力した数までフィボナッチ数列を見つけるために用語を反復するために使用されます。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です