Faster prime counting in python - python

I can't count prime all prime number <= n. My code broken(Execution Timed Out (12000 ms)) on n⩽10**10.
Can anyone help me solve the problem in python?
import numpy as np
def count_primes_less_than(n):
n +=1
assert n >= 6
sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool)
sieve[0] = False
for i in range(int(n ** 0.5) // 3 + 1):
if sieve[i]:
k = 3 * i + 1 | 1
sieve[((k * k) // 3)::2 * k] = False
sieve[(k * k + 4 * k - 2 * k * (i & 1)) // 3::2 * k] = False
return len(np.r_[((3 * np.nonzero(sieve)[0] + 1) | 1)]) + 2```

Related

Cant exit while loop on Simpson's Rule

I am trying to calculate an integral using Simpson's Rule formula.The catch is that the value of the integral is the one that satisfies the following condition:You find the Ih and Ih/2.If the absolute of (Ih-Ih/2)<error the loop is complete.Otherwise you repeat the process with half the h,which means it calculates the absolute of (Ih/2-Ih/4) and so on and so on.
while True:
###Ih part
h = (b - a) / N
y1 = np.linspace(a, b, N)
Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \
+ 4*sum(Ez11[1:N-1:2]) + Ez11[N-1])
#####Ih/2 part
h = (b-a)/(2*N)
y2 = np.linspace(a, b, 2*N)
Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
print(Ez22)
I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \
+ 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1])
# error condition I1=Ih I2=Ih/2
if np.abs(I11 - I22) < error:
break
else:
N = 2*N # h/2
print(np.abs(I11 - I22))
As far as I can tell,my approach should be correct.However the loop goes on and on,never to stop.
My code is as follows:
import numpy as np
from scipy.integrate import simps
import scipy.integrate as integrate
import scipy.special as special
# variables
a = 0
b = np.pi * 2
N = 100
ra = 0.1 # ρα
R = 0.05
fa = 35 * (np.pi / 180) # φα
za = 0.4
Q = 10 ** (-6)
k = 9 * 10 ** 9
aa = np.sqrt(ra ** 2 + R ** 2 + za ** 2)
error = 0.55 * 10 ** (-8)
h=(b-a)/N
I1 = np.nan
I11 = np.nan
#Simpsons section
############ Ez
#automated Simpson
while True:
###Ih part
y1 = np.linspace(a, b, N)
Ez1 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
print(len(Ez1))
I1 = simps(Ez1, y1)
#####Ih/2 part
y2 = np.linspace(a, b, 2*N)
Ez2 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
I2 = simps(Ez2, y2)
# error condition I1=Ih I2=Ih/2
if np.abs(I1 - I2) < error:
break
else:
N *= 2 # h/2
#custom-made Simpson
N = 100
while True:
###Ih part
h = (b - a) / N
y1 = np.linspace(a, b, N)
Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \
+ 4*sum(Ez11[1:N-1:2]) + Ez11[N-1])
#####Ih/2 part
h = (b-a)/(2*N)
y2 = np.linspace(a, b, 2*N)
Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
print(Ez22)
I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \
+ 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1])
# error condition I1=Ih I2=Ih/2
if np.abs(I11 - I22) < error:
break
else:
N = 2*N # h/2
print(np.abs(I11 - I22))
print(I1)
print(I11)
Simpson's Rule is as follows:
After a while it's stuck in this situation
The 5.23 part is the absolute diff of those 2 which shouldnt be that high.

How do I create a magic square matrix using python

A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the diagonal of the matrix remain same
This code is working only for odd numbers but not even numbers.
here's my code that i tried but it didn't work
`
def matrix(n):
m = [[0 for x in range(n)]
for y in range(n)]
i = n / 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of matrix:"))
matrix(n)
`
def matrix(n):
m = [[0 for x in range(n)]
for y in range(n)]
i = n / 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of matrix:"))
matrix(n)
def forEvenNumber(n):
arr = [[(n * y) + x + 1 for x in range(n)] for y in range(n)]
for i in range(0, n // 4):
for j in range(0, n // 4):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(0, n // 4):
for j in range(3 * (n // 4), n):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(3 * (n // 4), n):
for j in range(0, n // 4):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(3 * (n // 4), n):
for j in range(3 * (n // 4), n):
arr[i][j] = (n * n + 1) - arr[i][j];
for i in range(n // 4, 3 * (n // 4)):
for j in range(n // 4, 3 * (n // 4)):
arr[i][j] = (n * n + 1) - arr[i][j];
print("\nSum of all row, column and diagonals = ",
n * (n * n + 1) // 2, "\n")
for i in range(n):
for j in range(n):
print('%2d ' % (arr[i][j]), end=" ")
print()
def forOddNumber(n):
mgsqr = [[0 for x in range(n)]
for y in range(n)]
r = n // 2
c = n - 1
num = 1
while num <= (n * n):
if r == -1 and c == n:
c = n - 2
r = 0
else:
if c == n:
c = 0
if r < 0:
r = n - 1
if mgsqr[int(r)][int(c)]:
c = c - 2
r = r + 1
continue
else:
mgsqr[int(r)][int(c)] = num
num = num + 1
c = c + 1
r = r - 1
print("\nSum of all row, column and diagonals = ",
n * (n * n + 1) // 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (mgsqr[i][j]), end='')
print()
print("\nWELCOME:)\n")
n = int(input("Please Enter Number of Rows and Column (n*n): "))
if n%2==0:
forEvenNumber(n)
else:
forOddNumber(n)
print("\nThank You :)")
This should take in the even inputs and give the right outputs!

How can I write a program that prints a multiplication table of size m by n which is provided by the user in Python?

Examples:
m n: 2 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
m n: 4 2
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
3 * 1 = 3
3 * 2 = 6
4 * 1 = 4
4 * 2 = 8
I have written this code but i said "list assignment index out of range", how can I fix it? thanks
m, n = input('m n: ').split()
x = []
for i in range(0, int(m)):
for j in range(0, int(n)):
x[j] = int(m[i]) * int(n[j])
print(str(i) + ' * ' + str(j) + ' = ',x[j])
m, n = input('m n: ').split()
for i in range(1, int(m)+1):
for j in range(1, int(n)+1):
print(str(i) + ' * ' + str(j) + ' = ', i * j)

Using set theory to find the shape area in Python

So I'm given the following diagram:
And I'm being asked to find the area of each polygon given n. The area is basically the sum of all blue squares since each square has an area of 1. So when n = 1, the area is one. When n = 2, the area is 5. Because of the relationship between each polygon, I know that I could knock this down using set theory.
n Area(n)
1 1
2 A(n-1) + (4 * (n-1)) = 5
3 A(n-1) + (4 * (n-1)) = 13
4 A(n-1) + (4 * (n-1)) = 25
5 A(n-1) + (4 * (n-1)) = 41
However, I didn't have as much luck trying to represent this in code:
def shapeArea(n):
prev_output = 0
output = 0
if n == 1:
output = 1
elif n > 1:
for i in range(n):
prev_output = n-1 + (4 * (n-1))
output = prev_output + (4 * (n-1))
return output
For example: For n = 2, I'm getting an output of 9 instead of 5.
You were close :-)
Here are the small fix-ups:
def shapeArea(n):
output = 1
for i in range(1, n):
output += 4 * i
return output
Running this:
for n in range(1, 6):
print(n, shapeArea(n))
Gives this output:
1 1
2 5
3 13
4 25
5 41
of course with Gauss's theorem the code would look like this:
def ShapeArea(n):
return 2*(n**2) - (2*n)+1
In a recursive solution, it is much simple from your logic.
def shape_area(n):
if n == 1:
return 1
return shape_area(n-1) + 4*(n-1)
You can use Gauss' trick to make a closed-form formula:
2*Area(n) =
1 + 4 + 8 + 12 + ... + 4(n-1)
+
1 + 4(n-1) + 4(n-2) + 4(n-3) + ... + 4
--------------------------------------------------
2 + 4n + 4n + 4n + ... + 4n
= (n-1)4n + 2
= 4n^2 - 4n + 2
So Area(n) = 2n2 - 2n + 1
def shape_area(n):
return sum([1] + [4*i for i in range(1, n)])

Lucas probable prime test

I have been trying to implement the Baillie-PSW primality test for a few days, and have ran into some problems. Sepcifically when trying to use the Lucas probable prime test. My question is not about Baile, but on how to generate the correct Lucas sequence modulo some number
For the first two psudoprimes my code gives the correct result, eg for 323 and 377. However for the next psudoprime, both the standard implementation and the doubling version fails.
Trying to do modulo operations on V_1 completely breaks the doubling version of the Luckas sequence generator.
Any tips or suggestions on how to correctly implement the Lucas probable prime test in Python?
from fractions import gcd
from math import log
def luckas_sequence_standard(num, D=0):
if D == 0:
D = smallest_D(num)
P = 1
Q = (1-D)/4
V0 = 2
V1 = P
U0 = 0
U1 = 1
for _ in range(num):
U2 = (P*U1 - Q*U0) % num
U1, U0 = U2, U1
V2 = (P*V1 - Q*V0) % num
V1, V0 = V2, V1
return U2%num, V2%num
def luckas_sequence_doubling(num, D=0):
if D == 0:
D = smallest_D(num)
P = 1
Q = (1 - D)/4
V0 = P
U0 = 1
temp_num = num + 1
double = []
while temp_num > 1:
if temp_num % 2 == 0:
double.append(True)
temp_num //= 2
else:
double.append(False)
temp_num += -1
k = 1
double.reverse()
for is_double in double:
if is_double:
U1 = (U0*V0) % num
V1 = V0**2 - 2*Q**k
U0 = U1
V0 = V1
k *= 2
elif not is_double:
U1 = ((P*U0 + V0)/2) % num
V1 = (D*U0 + P*V0)/2
U0 = U1
V0 = V1
k += 1
return U1%num, V1%num
def jacobi(a, m):
if a in [0, 1]:
return a
elif gcd(a, m) != 1:
return 0
elif a == 2:
if m % 8 in [3, 5]:
return -1
elif m % 8 in [1, 7]:
return 1
if a % 2 == 0:
return jacobi(2,m)*jacobi(a/2, m)
elif a >= m or a < 0:
return jacobi(a % m, m)
elif a % 4 == 3 and m % 4 == 3:
return -jacobi(m, a)
return jacobi(m, a)
def smallest_D(num):
D = 5
k = 1
while k > 0 and jacobi(k*D, num) != -1:
D += 2
k *= -1
return k*D
if __name__ == '__main__':
print luckas_sequence_standard(323)
print luckas_sequence_doubling(323)
print
print luckas_sequence_standard(377)
print luckas_sequence_doubling(377)
print
print luckas_sequence_standard(1159)
print luckas_sequence_doubling(1159)
Here is my Lucas pseudoprimality test; you can run it at ideone.com/57Iayq.
# lucas pseudoprimality test
def gcd(a,b): # euclid's algorithm
if b == 0: return a
return gcd(b, a%b)
def jacobi(a, m):
# assumes a an integer and
# m an odd positive integer
a, t = a % m, 1
while a <> 0:
z = -1 if m % 8 in [3,5] else 1
while a % 2 == 0:
a, t = a / 2, t * z
if a%4 == 3 and m%4 == 3: t = -t
a, m = m % a, a
return t if m == 1 else 0
def selfridge(n):
d, s = 5, 1
while True:
ds = d * s
if gcd(ds, n) > 1:
return ds, 0, 0
if jacobi(ds, n) == -1:
return ds, 1, (1 - ds) / 4
d, s = d + 2, s * -1
def lucasPQ(p, q, m, n):
# nth element of lucas sequence with
# parameters p and q (mod m); ignore
# modulus operation when m is zero
def mod(x):
if m == 0: return x
return x % m
def half(x):
if x % 2 == 1: x = x + m
return mod(x / 2)
un, vn, qn = 1, p, q
u = 0 if n % 2 == 0 else 1
v = 2 if n % 2 == 0 else p
k = 1 if n % 2 == 0 else q
n, d = n // 2, p * p - 4 * q
while n > 0:
u2 = mod(un * vn)
v2 = mod(vn * vn - 2 * qn)
q2 = mod(qn * qn)
n2 = n // 2
if n % 2 == 1:
uu = half(u * v2 + u2 * v)
vv = half(v * v2 + d * u * u2)
u, v, k = uu, vv, k * q2
un, vn, qn, n = u2, v2, q2, n2
return u, v, k
def isLucasPseudoprime(n):
d, p, q = selfridge(n)
if p == 0: return n == d
u, v, k = lucasPQ(p, q, n, n+1)
return u == 0
print isLucasPseudoprime(1159)
Note that 1159 is a known Lucas pseudoprime (A217120).

Categories