I have the following python code:
a, b = 1, 1
for i in range(0, 100):
print a
a, b = b, a + b
It generates this: 1 1 2 3 5 8 etc
I wrote the same in c:
#include <stdio.h>
long long unsigned int a = 1, b = 1;
void main(){
for(int i = 0; i < 100; i++){
printf("%llu \n", a);
a = b, b = a + b;
}
}
It generates this: 1 1 2 4 8 16 32 etc
Why does the c program generate powers of 2 when it is using the exact same operations?
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Fibonacci Series is a pattern of numbers where each number is the result of addition of the previous two consecutive numbers . First 2 numbers start with 0 and 1. The third numbers in the sequence is 0+1=1. The 4th number is the addition of 2nd and 3rd number i.e. 1+1=2 and so on.
#Python program to generate Fibonacci series until 'n' value n = int(input("Enter the value of 'n': ")) a = 0 b = 1 sum = 0 count = 1 print("Fibonacci Series: ", end = " ") while(count <= n): print(sum, end = " ") count += 1 a = b…
a, b = b, a + b
in python packs the values b
and a + b
into a tuple, then unpacks it back into a
and b
.
C does not supports that feature, but rather use the comma to separate between assignments, so a = b, b = a + b
get translated as
a = b;
b = a + b;
where b
gets doubled every time because the assignment is not simultaneous.
To fix that you'd have to assign each variable separately:
b = a + b;
a = b - a; // a + b - a = b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With