Nth Fibonacci number - python-3.x

I am failed to print only the nth fibonacci number.
In my code, when the user said to print nth trem it print the series upto nth term but i want to get the output only the nth term
e.g
if I say num=4
out put should be 2
please guide
here is the code:
N= int(input("How many terms? "))
N1 = 0
N2 = 1
sum = 2
if N <= 0:
print("Plese enter a positive integer")
elif N == 1:
print("Fibonacci sequence:")
print(N1)
else:
print("Fibonacci sequence:")
print(N1,",",N2,end=' , ')
while sum < N:
Nth = N1 + N2
print(Nth,end=' , ')
N1 = N2
N2 = Nth
sum += 1

The print stmt should be outside the loop
N= int(input("How many terms? "))
N1 = 0
N2 = 1
sum = 2
if N <= 0:
print("Plese enter a positive integer")
elif N == 1:
print("Fibonacci sequence:")
print(N1)
else:
print("Fibonacci sequence:")
print(N1,",",N2,end=' , ')
while sum < N:
Nth = N1 + N2
N1 = N2
N2 = Nth
sum += 1
print(Nth,end=' , ')

Simpler code, from the "How to Think Like a Comptuer Scientist: Python" book,
def fibonacci (n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
Just call fibonacci passing your nth term as the argument.

to achieve that output you can simply decrease the value of n by 1 and then carry on all the computation.
For example:
def fib(n):
n = n-1
a, b = 0, 1
count = 1
while count <= abs(n):
next = a + b
a = b
b = next
count += 1
return a

Related

other options for solving tasks with list

Task:
Write a program that reads from the standard input and will return the:
sum
difference
product
of all elements in the given list.
Input
An integer n (1 <= n <= 500) that denotes the number of elements in the list. The following n integers are the next elements of the list.
Output
Three integers:
sum
difference
product
of all the elements of the list.
And these are my ideas, but I still get a mistake
from sys import stdin
def Simple_list_arithmetic():
print("Enter a positive number: ")
n = int(stdin.readline())
l = []
if n >= 1 and n <= 500:
for i in range(1, n+1):
l.append(i)
#print(l)
suma = 0
for add in range(0, len(l)):
suma = suma + l[add]
print(suma)
#return suma
difference = 2
for substract in range(0, len(l)):
difference = difference - l[substract]
print(difference)
#return difference
product = 1
for increase in range(0, len(l)):
product = product * l[increase]
print(product)
return suma, difference, product
else:
print("Wrong number.")
still wrong
suma = 0
q = [suma + l[add] for add in range(0, len(l))]
print(sum(q))
difference = 2
w = [difference - l[substract] for substract in range(0, len(l))]
print(list(w))
product = 1
e = [product * l[increase] for increase in range(0, len(l))]
print(sum(e))
still wrong
if n >= 1 and n <= 500:
for x in range(1, n+1):
print(x)
print("\n")
suma = 0
for add in range(1, n+1):
suma = suma + add
print(suma)
difference = 2
for substract in range(1, n+1):
difference = difference - substract
print(difference)
product = 1
for increase in range(1, n+1):
product = product * increase
print(product)
with map() and lambda still wrong
t = list(map(lambda add: suma + l[add], range(0, len(l))))
#return sum(t)
y = list(map(lambda increase: increase * l[increase], range(0, len(l))))
#print(y[-1])
#print(y)
try this:
x = int(input("Enter a positive number: "))
if x >= 1 and x <= 500:
sum = 0
for i in range(x,501):
sum +=i
print(sum)
diff = 2
for i in range(x,501):
diff -= i
print(diff)
prod = 1
for i in range(x, 501):
prod *= i
print(prod)

How to find number in list which has the biggest number of prime?

I want to write a program that receives 10 entries and at the end it should print the number that has the greatest number of prime factors along with the number of its prime factors in the output. And, if some of the inputs have the same condition, the program will print the biggest one.
The code that I wrote executed all conditions except the final condition.
How should I write a code for a case where two numbers have the same numbers of prime factors (when I want the bigger number to be my output)?
For example both 678 and 84 have 3 prime factors . The output of my code is 84, while I want the output to be 678 (the bigger number).
input:
123
43
54
12
76
84
98
678
543
231
Correct output:
678 3
but my output:
84 3
a = [0,0,0,0,0,0,0,0,0,0]
#a = [123,43,54,12,76,84,98,678,543,231]
b = [0,0,0,0,0,0,0,0,0,0]
def is_first (number):
Prime_number= 0
for m in range(1, (number //2)+1, 1):
if number % m == 0:
Prime_number += 1
if Prime_number > 1:
is_prime = 0
else:
is_prime = 1
return is_prime
for i in range(0,10,1):
a[i] = input()
for j in a:
numbers= 0
for k in range(2, int(j)//2, 1):
if int(j) % k == 0:
if is_first (k) == 1:
numbers += 1
b[a.index(j)] = numbers
index_of_same = [i for i, e in enumerate(b) if e == max(b)]
n = []
for t in index_of_same:
n.append(a[t])
print(str(max(n))+ ' ' + str(max(b)))
When you append the numbers that have the highest number of prime factors to the list n, you are storing them as strings and not integers. Hence when you do the max() function on n, which holds 84,678 and 231, 84 is returned. I would suggest you to convert the numbers using int(), when storing into n and then perform the max()function on it. Just tweak your code as under:
for t in index_of_same:
n.append(int(a[t]))
Your code is cumbersome IMO, so I'd like to suggest a simpler version:
def getNumOfFactors(n):
num = 0
factor = 1
while n > 1:
factor += 1
if n % factor == 0:
num += 1
n /= factor
while n % factor == 0:
n /= factor
return num
def getMaxValue(values):
factors = [getNumOfFactors(n) for n in values]
tuples = zip(factors,values)
sorted_tuples = sorted([tuple for tuple in tuples],key=lambda x: x[0])
max_tuples = [tuple for tuple in sorted_tuples if tuple[0] == sorted_tuples[-1][0]]
sorted_max_tuples = sorted([tuple for tuple in max_tuples],key=lambda x: x[1])
return sorted_max_tuples[-1]
maxValue = getMaxValue([123,43,54,12,76,84,98,678,543,231])
print(maxValue)

Given a positive integer, determine if it's the nth Fibonacci number for some n

I try to find out the index of a certain Fibonacci number. However my program returned to me this result "Your program took too long to execute. Check your code for infinite loops, or extra input requests" after typing in 1134903171.
num = 1
num_prev = 1
n = int(input())
i = 1
if n < 2:
print(1, 2)
else:
while i <= n + 2:
num_prev, num = num, num + num_prev
i += 1
if n == num:
print(i + 1)
break
elif i == n + 3:
print(-1)
#break`
Thank you guys. The problem of last code is that: if the number isn't a Fibonacci number and meanwhile it is too large, it will took to many loops for the calculation. As I used a web compiler to calculate, they do not allow such "infinity" loop to operate. Then I used a math methode to limite the loop.
import math
N=int(input())
root1=math.sqrt(5*N*N+4)
root2=math.sqrt(5*N*N-4)
i=1
num, num_prev = 1, 1
if root1%1==0 or root2%1==0:
while i <= N+2:
num_prev,num = num,(num+num_prev)
i+=1
if N==num:
print(i+1)
break
else:
print(-1)
But the best answer could be:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)

Logic to find out the prime factors of a number

I have created the below script to find out the prime factors of a number :
def check_if_no_is_prime(n):
if n <= 3:
return True
else:
limit = int(math.sqrt(n))
for i in range(2,limit + 1):
if n % i == 0:
return False
return True
def find_prime_factors(x):
prime_factors = []
if check_if_no_is_prime(x):
prime_factors.append(1)
prime_factors.append(x)
else:
while x % 2 == 0 and x > 1:
prime_factors.append(2)
x = x // 2
for i in range(3,x+1,2):
while x % i == 0 and x > 1:
if check_if_no_is_prime(i):
prime_factors.append(i)
x = x // i
if x <= 1:
return prime_factors
return prime_factors
no = int(input())
check = find_prime_factors(no)
print (check)
I am not sure whether this is the best and efficient way to do this ?
Can someone please point out any better way to do this ?
using sieve of erathnostanes to get all prime numbers from 2 to whatever limit inputted
def sieve(N):
from math import floor,sqrt
A=[1 for x in range(N+1)]
for count in range(2):
A[count]=0
for i in range(floor(sqrt(N))+1):
if A[i]==1:
for k in range(i*i,N+1,i):
A[k]=0
ans=list(enumerate(A))
res=[]
for (i,j) in ans:
if j==1:
res+=[i]
return res
print(sieve(100))
#my code

Finding prime numbers Python

I am making script , that finds prime numbers in specific range from 0 to X. Its works partially , it appends 2 and remove even numbers from list , but it doesnt go over 3.
cis = int(input("xd: "))
list1 = []
list2 = []
num = 2
while (num in range(0,cis)):
list1.append(num)
num += 1
continue
num2 = list1[0]
for i in list1:
if list1[0] in list2:
None
else:
list2.append(list1[0])
if i % num2 == 0:
list1.remove(i)
continue
if all(a % num2 != 0 for a in list1):
num2 += 1
continue
print (list1)
print (list2)
Thanks for help.

Resources