My two approaches to solve Fibonacci Last Digit Problem on Python - python-3.x

I am a newbie here. If I do something wrongly, please show me tolerance.
I tried to solve this problem:
Problem_Picture_1
Problem_Picture_2
My first solution didn't work:
# Uses python3
import sys
# Uses python3
def get_fibonacci_last_digit(n):
fib = [0, 1]
if n <= 1:
return n
for i in range(2, n):
current = (fib[i-1] + fib[i-2]) % 10
fib.append(current)
return fib[-1]
n = int(input())
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(get_fibonacci_last_digit(n))
But my second solution worked:
# Uses python3
def calc_fib(n):
fib = [0, 1]
if n <= 1:
return n
for i in range(2, n+1):
current = (fib[i-1] + fib[i-2]) % 10
fib.append(current)
return fib[-1]
n = int(input())
print(calc_fib(n))
What is the difference between these two approaches? Why didn't work my first solution? Please explain to me.
Edit:
When I worked my first approach, It's still running. It couldn't return a number
When I worked my first approach, It could return a number

The range(A, B) object iterates from A (inclusive) to B (exclusive). Eg.- range(2, 5) will return (2, 3, 4).
PS - Please use proper indentation while posting a question

Related

Why is my simple code taking so much time to execute when i give in large numbers as input?

I have written a simple code to print the largest prime factor of a given number from Project Euler. It works just fine for numbers like 24, but there is no response from the python shell for large numbers!
a=600851475143
b=[]
for i in range(2,600851475143):
if a%i==0:
if i==2:
b.append(i)
continue
for j in range(2,i+1):
if j==i:
b.append(i)
if i%j==0:
break
print(max(b))
print(b)
You can use an algorithm like this to get large factors of prime numbers:
import math
def LLL(N):
p = 1<<N.bit_length()-1
if N == 2:
return 2
if N == 3:
return 3
s = 4
M = pow(p, 2) - 1
for x in range (1, 100000):
s = (((s * N ) - 2 )) % M
xx = [math.gcd(s, N)] + [math.gcd(s*p+x,N) for x in range(7)] + [math.gcd(s*p-x,N) for x in range(1,7)]
try:
prime = min(list(filter(lambda x: x not in set([1]),xx)))
except:
prime = 1
if prime == 1:
continue
else:
break
return N/prime

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million

sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
The code i have return gives answer 143064094781 and the correct answer is 142913828922 but i can not figure out where i have gone wrong. So can any one help me.
Range's stop parameter is exclusive. This means that your code is only calculating j from 2 to 1 less than i**0.5. To fix this you can add 1, meaning that your end code will look a little like this, providing the correct output of 142913828922:
sum_ans=17
for i in range(11,2000000):
for j in range(2,int(i**0.5+1)):
if i%j==0:
break
else:
sum_ans+=i
print(sum_ans)
What about about this:
def isPrime(x):
prime = True
for i in range(2, x):
if x % i == 0:
prime = False
break
else:
continue
return prime
primes = (a for a in range(2, 2000000) if isPrime(a))
print(sum(primes))
# output
142913828922
This code will take a few minutes to execute. Buckle up!!
def sumPrimes(n):
sum =0
for i in range(2 ,n):
for j in range(2, int(i / 2) +1):
if (i % j) == 0:
break
else:
sum += i
return sum
print(sumPrimes(2000000))
If you iterating over all numbers below 2 million, you might as well sieve them using the Sieve of Eratoshenes:
from math import ceil, sqrt
def sieve(n):
nums = list(range(2,n+1))
primes = []
p = 2
k = 1+ ceil(sqrt(n))
while p < k:
primes.append(p)
nums = [num for num in nums[1:] if num % p > 0]
p = nums[0]
return primes + nums
Then sum(sieve(2000000)) evaluates to 142913828922. It takes about 5 seconds to run on my machine.

how to fix ' find the prime factors of a number' in Python

I tried to find the prime factor for a number by the following code:
def pf(n):
f=[]
while n != 1:
for i in range(2, n+1):
if n%i == 0:
f.append(i)
n //=i
return f
The output for pf(8) is [2, 4], rather than [2,2,2] as my expect.
The output for pf(16) is [2,4,2], rather than [2,2,2,2].
can anyone help me to figure out what's wrong with my code?
If you break inside the loop, you will get what you want :
def pf(n):
f=[]
while n != 1:
for i in range(2, n+1):
if n%i == 0:
f.append(i)
n //=i
break
return f
Why was it wrong ?
in you first for loop, 8 is can be divied by 2, so n is equal to 4. And when i is then equals to 4, then 4 is added as a prime factor
Other implementation:
I prefer this implementation :)
def pf(n):
f=[]
i = 2
while n != 1:
if n%i == 0:
f.append(i)
n //=i
else:
i += 1
return f
This implementation avoids you to recompute the numbers in range you already know is not dividable by.

Prime factorization of a number

I'm trying to write a program to find all the prime factors of a given number, and tried the following:
def factors(nr):
i = 2
factors = []
while i<nr:
if (nr%i)==0:
factors.append(i)
nr = nr/i
else:
i = i+1
return factors
My idea is the following. Start with i = 2, while i < the number, check if the module of the number and i = 0. If this is the case, add i to a list, and run the algorithm again, but now with the new number. However, my algorithm doesn't work. Any idea why?
I know that several right answers are posted on the site, but I would like to know why my program is incorrect.
Update
So if I let the programm run for example:
factors(38), yields [2].
factors(25), yields [5].
So it stops after it has added one number to the list.
The simplest change you can make to fix your problem is to change your while loop condition:
def factors(nr):
i = 2
factors = []
while i <= nr:
if (nr % i) == 0:
factors.append(i)
nr = nr / i
else:
i = i + 1
return factors
print factors(8)
print factors(9)
print factors(10)
Output
[2, 2, 2]
[3, 3]
[2, 5]
def ba(n):
pfa=[]
y=n
for i in range(n):
if (i!=0 and i!=1):
while (y%i==0):
pfa.append(i)
y=y/i
print(pfa)

Generating Fibonacci series in Python

I want to simple generate the fibonacci series in Python. But somehow i don't see the correct series. For example if i input 3 then the correct answer should come with the series : 1 1 2 3
Below is my code.Can someone please point out what is wrong with this :
def genfibonacci(no):
if no <= 1:
return no
else:
sum = genfibonacci(no - 1) + genfibonacci(no - 2)
print (sum)
return(sum)
number = int(input())
genfibonacci(number)
Thanks in advance.
Part of your problem is printing while you calculate (apart from if no <= 1)
If we remove the print, and just show what you get as a result this will help:
def genfibonacci(no):
if no <= 1:
sum = no
else:
sum = genfibonacci(no-1) + genfibonacci(no-2)
return sum
>>> [genfibonacci(i) for i in range(4)]
[0, 1, 1, 2]
>>> [genfibonacci(i) for i in range(5)]
[0, 1, 1, 2, 3]
This range starts at 0, so you can remove that if you want.
Since genfibonacci for say 4 will call 32 and 2, which in turn will call 2 and 1, the print statement you have will happen for the same number more than once.
And not at all for the no <= 1.
There are so many ways to calculate fibonacci sesries in python..
Example 1: Using looping technique
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
Example 2: Using recursion
def fibR(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print fibR(5)
Example 3: Using generators
a,b = 0,1
def fibI():
global a,b
while True:
a,b = b, a+b
yield a
f=fibI()
f.next()
f.next()
f.next()
f.next()
print f.next()
Example 4: Using memoization
def memoize(fn, arg):
memo = {}
if arg not in memo:
memo[arg] = fn(arg)
return memo[arg]
fib() as written in example 1.
fibm = memoize(fib,5)
print fibm
Example 5: Using memoization as decorator
class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, arg):
if arg not in self.memo:
self.memo[arg] = self.fn(arg)
return self.memo[arg]
#Memoize
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
Here the Simplest Fibonacci Series represnted:
#Fibonacci series in Short Code
#initilize the base list
ls2=[0,1]
#user input: How many wants to print
c=int(input('Enter required numbers:'))
#fibonacci Function to add last two elements of list
ls2.extend((ls2[i-1]+ls2[i-2]) for i in range(2,c))
#This will print recuired numbers of list
print(ls2[0:c])
If you Want Create Function Then:
#Fibonacci series in Short Code
#initilize the base list
ls2=[0,1]
#user input: How many wants to print
c=int(input('Enter required numbers:'))
#fibonacci Function to add last two elements of list
def fibonacci(c):
ls2.extend((ls2[i-1]+ls2[i-2]) for i in range(2,c))
#This will print required numbers of list
print(ls2[0:c])
fibonacci(c)
Fibonacci using Recursive Function in Python:
def fibonacci(n, fib1=0, fib2=1):
if n<=1:
print(fib1)
return
else:
print(fib1)
fib = fib1 + fib2
fib1 = fib2
fib2 = fib
fibonacci(n - 1, fib1, fib2)
number = int(input())
fibonacci(number)
There are different methods you can use but I use the method of recursion because here you have to code less
def fib(n):
if n<=1:
return n
else:
return fib(n-1)+fib(n-2)
n = int(input())
for i in range(n):
print(fib(i),sep=' ',end=' ')

Resources