Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci sequence works in python, but not in c?

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?

like image 633
Programah Avatar asked Jun 06 '17 15:06

Programah


People also ask

What is the logic of Fibonacci series in Python?

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.

What is the logic of Fibonacci series?

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.

How do you use Fibonacci sequence in while loop in Python?

#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…


1 Answers

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
like image 64
Uriel Avatar answered Oct 06 '22 19:10

Uriel