I’ve reading the python code of Fibonacci sequence and others code as well. but the part I can’t even explain exactly how it works and how did he come up with this solution that makes the code to work like coding prime factorization number
For Fibonnaci squence:
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b # can;
print()
fib(1000)
Prime factorization:
def largest_prime_factor(n):
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
return n
It’s explained with a little mathematics. Each step in the while loop either considers the next factor, or divides out the factor i from n. Things are kicked off from a candidate factor of 2, so at each step all smaller factors have already been divided out, so what remains must be the largest prime factor. If i > sqrt(n) then even if i was a factor n, the corresponding quotient q (s.t. n = i*q) would’ve already been considered in the iteration.
They’re both canonical standard algorithms too. Even without the maths, it’s fine to look up a reference implementation from the Computer Science literature (e.g. Knuth, et al.)
I still don’t get it; I understand the mathematics but the code looking overwhelm. How do I come up with this solution with my code if I don’t learn anything from this.
… then you’re one step ahead of the curve (the concept of variables changing values should come second nature which in a program, are ubiquitous).
For the first code snippet (function fib), you just have to take note that once you hit the while keyword, this implies a loop. The conditional statement a < n means that the loop should keep repeating so long as a is less n. If you step carefully through each line, tabulating the values for each iteration (loop), it should be easy to follow.
Sometimes, it helps if you spread out the lines a bit so that the script can be read more clearly.
def fib(n):
a, b = 0, 1 # a = 0, and b = 0; these are the initial values
while a < n: # <---- begin loop iterations
print(a, end=' ') # this only prints the value of `a`
a, b = b, a + b # <---- end loop iterations
print(f'\n{a}, {b}')
fib(6) # Entered 6 but loop states less than. So, less than 6 is 5
Output:
>>> 0 1 1 2 3 5
8, 13
Here are the tabulated values of a and b through the first 5 loops.
I am not familiar with the names you have mentioned. However, the source that I used for learning Python is (5th Ed actually but 6th Ed is the most available version with up to date information):
You can use it as a curriculum as it is comprehensive and covers just about all of the Python fundamentals. If you need additional resources on a particular topic, google is your best friend. Just stay on track and read the book in a linear manner (at least that is the way I covered it) and it should work just fine.