9k5v1+2/3?*1-^5v/0k2/p
Probieren Sie es online!
Oder speichern Sie das Programm in einer Datei und führen Sie es durch Eingabe aus
dc -f *filename*
Das Programm akzeptiert eine nicht negative ganze Zahl n für stdin und gibt die Summe der ersten n geraden Fibonacci-Zahlen für stdout aus. (Die Fibonacci-Sequenz beginnt gemäß den Beispielen des OP mit 0.)
Dieses Programm verwendet die Formel (F (3n-1) -1) / 2 für die Summe der ersten n geraden Fibonacci-Zahlen, wobei F die übliche Fibonacci-Funktion ist, gegeben durch F (0) = 0, F (1) = In 1 ist F (n) = F (n - 2) + F (n - 1) für n> = 2.
dc ist ein stapelbasierter Rechner. Hier ist eine detaillierte Erklärung:
9k # Sets the precision to 9 decimal places (which is more than sufficient).
5v # Push the square root of 5
1+ # Add 1 to the number at the top of the stack.
2/ # Divide the number at the top of the stack by 2.
Zu diesem Zeitpunkt befindet sich die Zahl (1 + sqrt (5)) / 2 oben auf dem Stapel.
3 # Push 3 on top of the stack.
? # Read a number from stdin, and push it.
\* # Pop two numbers from the stack, multiply them, and push the product
1- # Subtract 1 from the number at the top of the stack.
Zu diesem Zeitpunkt befindet sich 3n-1 oben im Stapel (wobei n die Eingabe ist), und (1 + sqrt (5)) / 2 befindet sich an zweiter Stelle von oben.
^ # Pop two numbers from the stack (x, then y), compute the power y^x, and push that back on the stack.
5v/ # Divide the top of the stack by sqrt(5).
Zu diesem Zeitpunkt ist die Zahl oben im Stapel (((1 + sqrt (5)) / 2) ^ (3n-1)) / sqrt (5). Die nächste Ganzzahl zu dieser Zahl ist F (3n-1). Beachten Sie, dass F (3n-1) immer eine ungerade Zahl ist.
0k # Change precision to 0 decimal places.
2/ # Divide the top of the stack by 2, truncating to an integer.
p # Print the top of the stack on stdout.