I´m solving a problem in which i have to print all the fibonacci numbers such that:
a <= f <= b
And i would like to start them by the smallest fibonacci number that is greater than or equal to a, in order to make my program run faster. For that, i need to define a variable "n", such that the nth Fibonacci number satisfies the condition above (smallest one that is greater than or equal to a). To define such variable, i need to find the smallest "n" that satisfies the fibonacci(n) general term equation.
I tried to find it by making a for loop, but it just ends up being as slow as if i started to check from the first Fibonacci Number. Anyone has any ideas on how to define it efficiently?
P.S. Here is my attempted code:
from math import sqrt, log, ceil
def Fibo(n):
if n == 1: return 1
elif n == 2: return 2
return Fibo(n-1) + Fibo(n-2)
while True:
try:
a, b = [int(i) for i in input().split()]
cont = 0
phi = (sqrt(5) + 1) / 2
i = ceil(log(a * sqrt(5), phi))
if Fibo(i-1) >= a: i -= 1
elif Fibo(n) < a: i += 1
while True:
if a <= Fibo(i) <= b: cont += 1
elif Fibo(i) > b:
break
i -= 1
print(cont)
except input() == "0 0":
break
Probably the most useful formula for your purpose for F(n), the nth Fibonacci number, is
from math import sqrt
phi = (sqrt(5) + 1) / 2 # the golden ratio
F(n) = round(phi**n / sqrt(5))
Therefore, one formula to get the value of n for a given value of a is
from math import sqrt, log, ceil
phi = (sqrt(5) + 1) / 2 # the golden ratio
n = ceil(log(a * sqrt(5), phi))
Due to approximation and rounding issues, you should check the values of n-1, n, and n+1 to ensure you got exactly the desired value. If you do this often, you should pre-define variables holding the value of the golden ratio and of the square root of five. If your value of a is too large for the float type to store it accurately, you would need a more complicated routine to handle the larger number.
Related
I want to write a function of cos(x) using the Taylor Expansion, but not using the math.factorial function.
I defined the factorial of 2i as:
def factorial_two(i):
if i < 0:
#Handling negative numbers
print("Error: can't compute the factorial of a negative number!")
return None
elif i == 0:
#The special case i = 0
return 1
else:
i = i * 2
#The general case
fact = 1
while i > 0:
fact = fact * i
i = i - 1
return fact
Then I defined the approximation of cosine as:
def cosine_approx(x,n):
sum = 0
for i in range(0, n+1):
sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
return sum
When I run this for any x and any n I always get 1.0 as the result. When I tried the exact same function for cosine_approx(x,n), but instead use the basic math.factorial(2*i) I get the correct results. So the question is, where did I go wrong with by definition? Or am I not using it correctly?
Thank you in advance.
your code has an error you put return sum in the for loop!!
so sum always be 1.0 and returend.
you should put that out of for loop.
for i in range(0, n+1):
sum += ((-1) ** i) * (x**(2*i)/ factorial_two(i))
return sum
like that.
So here is the challenge: I am given four numbers: a,b,c,d. Then the number n is given which describes how many numbers to check will be. Then these numbers are inputted and the goal is to find which probability that number will be gotten if multiply two random numbers one from the range a to b and one from c to d range. Finally, I need to output that probability in 'p/q' format. I figured out the solution and it works but the problem is when working with bigger numbers it uses too much time. I also have another solution where I first create a list with all possible combinations but in that case it uses too much memory.
from math import gcd
a,b,c,d = (map(int,input().split(" ")))
combs_quantity = (b-a+1)*(d-c+1)
def findProb(z):
repeats = 0
nec_mulps = [z//x for x in range(a,b+1) if z%x == 0]
for n in nec_mulps:
if n in range(c,d+1):
repeats+=1
probGCD = gcd(repeats,combs_quantity)
return str(repeats//probGCD) + "/" + str(combs_quantity//probGCD)
probability = []
n = int(input())
for i in range(n):
probability.append(findProb(int(input())))
for p in probability:
print(p)
Get all divisors of n
For every divisor Z that belongs to range a..b check whether complementary divisor n//Z lies in range c..d
#MBo said above that complexity is sqrt(z). You can to calculcate repeats as:
divisors = []
i = 1
while i * i <= z:
if z % i == 0:
divisors.append(i)
if i * i < z:
divisors.append(z // i)
i += 1
repeats = 0
for divisor in divisors:
if a <= divisor <= b and c <= z // divisor <= d:
repeats += 1
I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.
I'm creating all the necessary functions for RSA algorithm. Unfortunately i can't seem to a make proper Carmichael function.
These are the functions that i've written:
def gcd(a, b): # Greatest Common Divisor Generator (Euclidean Algorithm)
while b != 0: # While remainder exists
t = b # Initially r[k-1]
b = a % t # Initially r[k] = r[k-2] mod r[k-1] (where r[k-2] is a)
a = t # Predecessor of remainder (b)
return a
def phi(n): # Leonard Euler's Totient Function
y = 0
for k in range(1, n + 1): # Phi(+n) is the number of integers k in the range (1 <= k >= n)...
if gcd(n, k) == 1: # for which gcd(n, k) = 1
y += 1
return y
def carmichael(n): # Robert Daniel Carmichael's Function
y = (phi(n) * 1/2) if (n > 4 and ((n & (n - 1)) == 0)) else phi(n) # phi(n) * 1/2 if 2^x = n, else phi(n) * 1
return y
I'm using totient function for number generation. From my knowledge there is a simple rule, If number is power of 2 and it's greater than 4, Amount of it's prime numbers shall be halved, otherwise it's equal to phi(n).
The rule above is perfectly working in my code, For example, if the input value is 8, these are the results:
phi(8) = 4
carmichael(8) = 2
But the problem is, Carmichael function is also halving other numbers for some reason, for example if input is 12, this is what my functions return:
phi(12) = 4
carmichael(12) = 4
But this is how it should look like:
phi(12) = 4
carmichael(12) = 2
Why is this happening? Perhaps non-prime odd numbers should be treated differently? Is there something that i need to add to my function?
Thank you!
First we create the gcd function to calculate greatest common divisor of 2 numbers, we will need it later in lambda function.
def gcd(a,b):
while (a>0):
b=b%a
(a,b)=(b,a)
return b
Then we look at how carmichael function works.
Let n be a positive integer. Then λ(n) is defined to be the smallest positive integer k such that
a^k≡1(mod n)
for all a such that gcd(a,n)=1.
Note that we are looking for k, the values of a is determined once we have n.
Now we initialize the function with default condition
n=int(n)
k=2
a=1
alist=[]
To find all a values we use gcd(a,n)=1 to test whether a and n have the greatest common divisor as 1, which means they are coprime.
If not, a++
if gcd(a,n)==1, we store this value to the list of a and test next a until we test all a<=n
while not ((gcd(a,n))==1):
a=a+1
while ((gcd(a,n))==1) & (a<=n) :
alist.append(a)
a=a+1
while not ((gcd(a,n))==1):
a=a+1
Ok now we have all a in the list alist, look back at definition
the smallest positive integer k such that
a^k≡1(mod n)
First we count the number of a, which is the length of alist
timer=len(alist)
Then we use
if (a**k)%n==1:
to test whether this k makes a^k≡1(mod n) for all a value in alist. We construct a loop
for a in alist:
if (a**k)%n==1:
timer=timer-1
if timer <0:
break
pass
else:
timer=len(alist)
k=k+1
to test all k number from 2, if it doesnot meet requirement, we do k=k+1
Now we have the whole function as following
def carmichael(n):
n=int(n)
k=2
a=1
alist=[]
while not ((gcd(a,n))==1):
a=a+1
while ((gcd(a,n))==1) & (a<=n) :
alist.append(a)
a=a+1
while not ((gcd(a,n))==1):
a=a+1
timer=len(alist)
while timer>=0:
for a in alist:
if (a**k)%n==1:
timer=timer-1
if timer <0:
break
pass
else:
timer=len(alist)
k=k+1
return k
I'm totally new to Python and I'm trying to print the solution for a recursive sequence:
#Input sequence variables
a = float(raw_input("type in a = "))
n0 = int(raw_input("type in n_0 = "))
n1 = int(raw_input("type in n_1 = "))
y0 = float(raw_input("type in y_0 = "))
#Define function y_n (forward iteration)
def yn(n):
if (n==0):
return y0
else:
return (1/n)-a*yn(n-1)
#backward iteration
def yn_back(n):
return (1/a)*((1/n)-yn(n-1))
if(n1>=n0):
for i in range(n0,n1+1):
print(yn(i))
else:
for i in range(n0,n1+1):
print(yn_back(i))
But if I run this script with a=5, n0=1, n1=30 and y0=log(5/6)=0.182322 the solutions are very high (from 0.08839 to 3.29e+18) and the values are negative for even n. The solution is right for n=1. For other n, the (1/n) in the definition of yn(n) seems to be ignored.
Can someone help me?
Thanks a lot!
n is probably an integer, so 1/n is returning 0 for n greater than 1:
>>> 1/1
1
>>> 1/2
0
>>> 1.0/2
0.5
To make sure you're using float division, change 1 to 1.0 wherever you calculate 1/n:
(1.0/n)
Or convert n into a float.