Can't change miller rabin formula to calculate error? - python

How would I determine the numbers that aren't prime, and that my equation says it is prime?
Lets say 100-1000 numbers that are prime, and by definition from wikipedia, "which detect all composites (once again, this means: for every composite number n, at least 3/4 (Miller–Rabin) or 1/2 (Solovay–Strassen) of numbers a are witnesses of compositeness of n). "
How would I change the formula for error estimate?
from random import randrange
def miller-rabin(i, k):
"""
Miller Rabin written in Python
:param i: i is the number to check for primality
:param k: is the security value
:return: True is the number is prime, false if not
"""
#base case 1
if i < 2 or i % 2 == 0:
return False
#case 2
if i == 2:
return True
r = 0
s = i - 1
#create initial equation n-1 = 2^(u*r)
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = randrange(2, i-1)
x = pow(a, s, i)
if x == 1 or x == i - 1:
continue
for _ in range( r - 1):
x = pow(x, 2, i)
if x == i - 1:
break
else:
return False
return True
print(millerR(10, 5))

Related

Printing the sum of prime divisors of each number in a given range in python

Here's my code for printing the sum of prime divisors of each number between 18 to 25. But it is only printing 5.
For example:
18 has prime factors 2, 3 hence sum = 5,
19 is prime, hence sum of factors = 0,
20 has prime factors 2 and 5, hence sum = 7,
21 has prime factors 3 and 7, hence sum = 10,
22 has prime factors 2 and 11, hence sum = 13,
23 is prime. hence sum = 0,
24 has prime factors 2 and 3, hence sum = 5,
25 has prime factor 5, hence sum = 5
Therefore, it should print [5,0,7,10,13,0,5,5]
I believe I should use break statement but i tried it didn't work. As I am beginner in python, any kind of help much appreciated.
def isPrime(n):
i = 2
while i * i <= n:
# n has a factor, hence not a prime
if (n % i == 0):
return False
i += 1
# we reach here if n has no factors
# and hence n is a prime number
return True
def summ(l, r):
summ = 0
arrayofdivisors = []
arrayofsum = []
# iterate from lower to upper
for i in range(l, r + 1) :
# if i is prime, it has no factors
if (isPrime(i)) :
continue
for j in range(2, i):
# check if j is a prime factor of i
if (i % j == 0 and isPrime(j)) :
arrayofdivisors.append(j)
if(len(arrayofdivisors)>1):
ans = sum(arrayofdivisors)
arrayofsum.append(ans)
return arrayofsum
# Driver code
if __name__ == "__main__":
l = 18
r = 25
print(summ(l, r))
Try this
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def Sum(N):
SumOfPrimeDivisors = [0] * (N + 1)
for i in range(2, N + 1) :
if (SumOfPrimeDivisors[i] == 0) :
for j in range(i, N + 1, i) :
SumOfPrimeDivisors[j] += i
return SumOfPrimeDivisors[N]
arr=[]
for i in range(18,26):
if isPrime(i):
arr.append(0)
else:
arr.append(Sum(i))
print(arr)
It's almost impossible to tell because of the way you've formatted things, but the problem here is that your "return" statement is indented one position too far. Thus, you return at the end of the first loop, before it has a chance to check anything else. Un-indent the return arrayofsum and it should work.
Then, you are initializing arrayofdivisors outside the main loop, so it just kept getting larger and larger. Then, you weren't adding 0 to the list for prime numbers, as your spec required.
Note that if statements in Python do not need parentheses, like they do in C.
def isPrime(n):
i = 2
while i * i <= n:
# n has a factor, hence not a prime
if n % i == 0:
print(n,'not prime')
return False
i += 1
# we reach here if n has no factors
# and hence n is a prime number
print(n,"prime")
return True
def summ(l, r):
# iterate from lower to upper
arrayofsum = []
for i in range(l, r + 1) :
arrayofdivisors = []
# if i is prime, it has no factors
if isPrime(i):
arrayofsum.append(0)
continue
for j in range(2, i):
# check if j is a prime factor of i
if i % j == 0 and isPrime(j):
arrayofdivisors.append(j)
arrayofsum.append( sum(arrayofdivisors) )
return arrayofsum
# Driver code
if __name__ == "__main__":
l = 18
r = 25
print(summ(l, r))

Having trouble with implementeing the Miller-Rabin compositeness in Python

I'm not sure if this is the right place to post this question so if it isn't let me know! I'm trying to implement the Miller Rabin test in python. The test is to find the first composite number that is a witness to N, an odd number. My code works for numbers that are somewhat smaller in length but stops working when I enter a huge number. (The "challenge" wants to find the witness of N := 14779897919793955962530084256322859998604150108176966387469447864639173396414229372284183833167 in which my code returns that it is prime when it isn't) The first part of the test is to convert N into the form 2^k + q, where q is a prime number.
Is there some limit with python that doesn't allow huge numbers for this?
Here is my code for that portion of the test.
def convertN(n): #this turns n into 2^x * q
placeholder = False
list = []
#this will be x in the equation
count = 1
while placeholder == False:
#x = result of division of 2^count
x = (n / (2**count))
#y tells if we can divide by 2 again or not
y = x%2
#if y != 0, it means that we cannot divide by 2, loop exits
if y != 0:
placeholder = True
list.append(count) #x
list.append(x) #q
else:
count += 1
#makes list to return
#print(list)
return list
The code for the actual test:
def test(N):
#if even return false
if N == 2 | N%2 == 0:
return "even"
#convert number to 2^k+q and put into said variables
n = N - 1
nArray = convertN(n)
k = nArray[0]
q = int(nArray[1])
#this is the upper limit a witness can be
limit = int(math.floor(2 * (math.log(N))**2))
#Checks when 2^q*k = 1 mod N
for a in range(2,limit):
modu = pow(a,q,N)
for i in range(k):
print(a,i,modu)
if i==0:
if modu == 1:
break
elif modu == -1:
break
elif i != 0:
if modu == 1:
#print(i)
return a
#instead of recalculating 2^q*k+1, can square old result and modN that.
modu = pow(modu,2,N)
Any feedback is appreciated!
I don't like unanswered questions so I decided to give a small update.
So as it turns out I was entering the wrong number from the start. Along with that my code should have tested not for when it equaled to 1 but if it equaled -1 from the 2nd part.
The fixed code for the checking
#Checks when 2^q*k = 1 mod N
for a in range(2,limit):
modu = pow(a,q,N)
witness = True #I couldn't think of a better way of doing this so I decided to go with a boolean value. So if any of values of -1 or 1 when i = 0 pop up, we know it's not a witness.
for i in range(k):
print(a,i,modu)
if i==0:
if modu == 1:
witness = False
break
elif modu == -1:
witness = False
break
#instead of recalculating 2^q*k+1, can square old result and modN that.
modu = pow(modu,2,N)
if(witness == True):
return a
Mei, i wrote a Miller Rabin Test in python, the Miller Rabin part is threaded so it's very fast, faster than sympy, for larger numbers:
import math
def strailing(N):
return N>>lars_last_powers_of_two_trailing(N)
def lars_last_powers_of_two_trailing(N):
""" This utilizes a bit trick to find the trailing zeros in a number
Finding the trailing number of zeros is simply a lookup for most
numbers and only in the case of 1 do you have to shift to find the
number of zeros, so there is no need to bit shift in 7 of 8 cases.
In those 7 cases, it's simply a lookup to find the amount of zeros.
"""
p,y=1,2
orign = N
N = N&15
if N == 1:
if ((orign -1) & (orign -2)) == 0: return orign.bit_length()-1
while orign&y == 0:
p+=1
y<<=1
return p
if N in [3, 7, 11, 15]: return 1
if N in [5, 13]: return 2
if N == 9: return 3
return 0
def primes_sieve2(limit):
a = [True] * limit
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
yield i
for n in range(i*i, limit, i):
a[n] = False
def llinear_diophantinex(a, b, divmodx=1, x=1, y=0, offset=0, withstats=False, pow_mod_p2=False):
""" For the case we use here, using a
llinear_diophantinex(num, 1<<num.bit_length()) returns the
same result as a
pow(num, 1<<num.bit_length()-1, 1<<num.bit_length()). This
is 100 to 1000x times faster so we use this instead of a pow.
The extra code is worth it for the time savings.
"""
origa, origb = a, b
r=a
q = a//b
prevq=1
#k = powp2x(a)
if a == 1:
return 1
if withstats == True:
print(f"a = {a}, b = {b}, q = {q}, r = {r}")
while r != 0:
prevr = r
a,r,b = b, b, r
q,r = divmod(a,b)
x, y = y, x - q * y
if withstats == True:
print(f"a = {a}, b = {b}, q = {q}, r = {r}, x = {x}, y = {y}")
y = 1 - origb*x // origa - 1
if withstats == True:
print(f"x = {x}, y = {y}")
x,y=y,x
modx = (-abs(x)*divmodx)%origb
if withstats == True:
print(f"x = {x}, y = {y}, modx = {modx}")
if pow_mod_p2==False:
return (x*divmodx)%origb, y, modx, (origa)%origb
else:
if x < 0: return (modx*divmodx)%origb
else: return (x*divmodx)%origb
def MillerRabin(arglist):
""" This is a standard MillerRabin Test, but refactored so it can be
used with multi threading, so you can run a pool of MillerRabin
tests at the same time.
"""
N = arglist[0]
primetest = arglist[1]
iterx = arglist[2]
powx = arglist[3]
withstats = arglist[4]
primetest = pow(primetest, powx, N)
if withstats == True:
print("first: ",primetest)
if primetest == 1 or primetest == N - 1:
return True
else:
for x in range(0, iterx-1):
primetest = pow(primetest, 2, N)
if withstats == True:
print("else: ", primetest)
if primetest == N - 1: return True
if primetest == 1: return False
return False
# For trial division, we setup this global variable to hold primes
# up to 1,000,000
SFACTORINT_PRIMES=list(primes_sieve2(100000))
# Uses MillerRabin in a unique algorithimically deterministic way and
# also uses multithreading so all MillerRabin Tests are performed at
# the same time, speeding up the isprime test by a factor of 5 or more.
# More k tests can be performed than 5, but in my testing i've found
# that's all you need.
def sfactorint_isprime(N, kn=5, trialdivision=True, withstats=False):
from multiprocessing import Pool
if N == 2:
return True
if N % 2 == 0:
return False
if N < 2:
return False
# Trial Division Factoring
if trialdivision == True:
for xx in SFACTORINT_PRIMES:
if N%xx == 0 and N != xx:
return False
iterx = lars_last_powers_of_two_trailing(N)
""" This k test is a deterministic algorithmic test builder instead of
using random numbers. The offset of k, from -2 to +2 produces pow
tests that fail or pass instead of having to use random numbers
and more iterations. All you need are those 5 numbers from k to
get a primality answer. I've tested this against all numbers in
https://oeis.org/A001262/b001262.txt and all fail, plus other
exhaustive testing comparing to other isprimes to confirm it's
accuracy.
"""
k = llinear_diophantinex(N, 1<<N.bit_length(), pow_mod_p2=True) - 1
t = N >> iterx
tests = []
if kn % 2 == 0: offset = 0
else: offset = 1
for ktest in range(-(kn//2), (kn//2)+offset):
tests.append(k+ktest)
for primetest in range(len(tests)):
if tests[primetest] >= N:
tests[primetest] %= N
arglist = []
for primetest in range(len(tests)):
if tests[primetest] >= 2:
arglist.append([N, tests[primetest], iterx, t, withstats])
with Pool(kn) as p:
s=p.map(MillerRabin, arglist)
if s.count(True) == len(arglist): return True
else: return False
sinn=14779897919793955962530084256322859998604150108176966387469447864639173396414229372284183833167
print(sfactorint_isprime(sinn))

How do you find the first m twin primes?

My program is supposed to find the first m twin primes and print that they are.
def isItPrime(n):
tests = primes.copy()
while len(tests) != 0:
if n % tests[-1] == 0:
return False
elif n % tests[-1] != 0:
tests.pop()
if len(tests) == 0:
primes.append(n)
return True
def findTwinPrimes(a , b):
if isItPrime(a) == True:
if isItPrime(b) == True:
if b - a == 2:
print(a, "-", b, "is a twin prime")
def firstMTwinPrimes(m):
o = 0
i = 1
if o < m :
print(i)
k = 3
l = 5
findTwinPrimes(k,l)
k += 1
l += 1
o += 1
firstMTwinPrimes(7)
Currently, it runs without errors but also does not work. The i is to check how many times the program runs and it only runs once. I do not know why becuase if o is less than m it should run again. Also for 3 and 5, they are twin primes but it doesn't work for them. isItPrime is already implemented to check if a number is prime or not. It returns the answer.
please, post your code with function and error
otherwise, try this:
def printTwinPrime(n):
prime = [True for i in range(n + 2)]
p = 2
while (p * p <= n + 1):
# If prime[p] is not changed,
# then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n + 2, p):
prime[i] = False
p += 1
# check twin prime numbers
# display the twin prime numbers
for p in range(2, n-1):
if prime[p] and prime[p + 2]:
print("(",p,",", (p + 2), ")" ,end='')
# driver program
if __name__=='__main__':
# static input
n = 7
# Calling the function
printTwinPrime(n)
As #JayMody notes, your isItPrime() is broken. We can make it work as intended, but the way it relies on being called with increasing arguments, and its use of a global primes list, are problems. (I.e. consider first calling isItPrime(22) followed by isItPrime(6))
#JohanC's answer, which you accepted, doesn't maintain a global prime list, instead doing more divisions than necessary by testing all numbers from 2 to the number. This is far less efficient than what you were attempting to implement. I think we can salvage your original intent, and not expose a non-general isItPrime() test, by making one function internal to the other:
def firstMTwinPrimes(m):
primes = [2]
def isItPrime(n):
for prime in primes:
if prime * prime > n:
break
if n % prime == 0:
return False
primes.append(n)
return True
number = 3
count = 0
while count < m:
for n in range(number, number + 3, 2):
if n == primes[-1]:
continue
if not isItPrime(n):
break
else: # no break
print(number, "-", number + 2, "are twin primes")
count += 1
number += 2
We have to be careful not to add a prime to the list twice when it's tested as a lower and upper number. You'll find this approach is a couple of orders of magnitude faster than #JohanC's answer when M exceeds a hundred. You were on the right track.
The sieve-based solution #AlokMishra posted is faster still, but it is designed to find all pairs up to some number, not some number of pairs as you specified.
Some remarks:
You need to change your if o < m to a while loop: while o < m. With only the if-test, findTwinPrimes is only called once. You need to call it again and again until you have enough twin primes. Inside that while-loop, you need to increment o only when you really found twin primes. Therefore, findTwinPrimes should return True when it found a twin prime, and False when it didn't. Also, k=3; l=5 should be put before the start of the while-loop, so they can be incremented inside the loop.
Instead of if isItPrime(a) == True: it is better to just write if isItPrime(a):. That has the same effect and is more readable.
You have a variable i that you just give a value of 1 and print, but don't do anything useful with. You can leave it out.
Python code is more readable if you indent with four spaces instead of only 2
Here is the adapted code:
def isItPrime(p):
for i in range(2, p):
if p % i == 0:
return False
return True
def findTwinPrimes(a, b):
if isItPrime(a):
if isItPrime(b):
if b - a == 2:
print(a, "-", b, "is a twin prime")
return True
return False
def firstMTwinPrimes(m):
o = 0
k = 3
l = 5
while o < m:
if findTwinPrimes(k, l):
o += 1
k += 1
l += 1
firstMTwinPrimes(7)
Output:
3 - 5 is a twin prime
5 - 7 is a twin prime
11 - 13 is a twin prime
17 - 19 is a twin prime
29 - 31 is a twin prime
41 - 43 is a twin prime
59 - 61 is a twin prime
PS: If you want, you can write
if isItPrime(a):
if isItPrime(b):
if b - a == 2:
as
if isItPrime(a) and isItPrime(b) and b - a == 2:

Function to evaluate validity of numerical palindrome for floating point numbers using Python

So there are plenty of algorithms to evaluate whether an int is a palindrome, i.e.
def ReverseNumber(n, partial=0):
if n == 0:
return partial
return ReverseNumber(n // 10, partial * 10 + n % 10)
or this one:
def isPalindrome(x):
if (x < 0):
return False
div = 1
while (x / div >= 10):
div *= 10
while (x != 0):
l = x / div
r = x % 10
if (l != r):
return False
x = (x % div) / 10
div /= 100
return True
However what I'd like to do is assess whether a number such as 1.01 or 22.22 and so on, whether such numbers are themselves palindromes.
How could either of those algorithms above be adapted to function for floats in addition to ints?
This is the code I'm using to call it:
import sys
# This method determines whether or not the number is a Palindrome
def isPalindrome(x):
x = str(x).replace('.','')
a, z = 0, len(x) - 1
while a < z:
if x[a] != x[z]:
return False
a += 1
z -= 1
return True
if '__main__' == __name__:
trial = int(sys.argv[1])
# check whether we have a Palindrome
if isPalindrome(trial):
print("It's a Palindrome!")
The simplest thing to do is just convert the number to a string, then compare characters from the ends to the middle. The string conversion is less expensive than repeated multiplications and divisions.
def isPalindrome(x):
x = str(x).replace('.','')
a, z = 0, len(x) - 1
while a < z:
if x[a] != x[z]:
return False
a += 1
z -= 1
return True

Fast Prime Generator besides Sieve

I recently made this bit of code, but wonder if there is a faster way to find primes (not the Sieve; I'm still trying to make that). Any advice? I'm using Python and I'm rather new to it.
def isPrime(input):
current = 0
while current < repetitions:
current = current + 2
if int(input) % current == 0:
if not current == input:
return "Not prime."
else:
return "Prime"
else:
print current
return "Prime"
i = 1
primes = []
while len(primes) < 10001:
repetitions = int(i)-1
val = isPrime(i)
if val == "Prime":
primes.append(i)
i = i + 2
print primes[10000]
here is a function that detect if x is prime or not
def is_prime(x):
if x == 1 or x==0:
return False
elif x == 2:
return True
if x%2 == 0:
return False
for i in range(3, int((x**0.5)+1), 2):
if x%i == 0:
return False
return True
and another implementation that print prime numbers < n
def prime_range(n):
print(2)
for x in range(3, n, 2):
for i in range(3, int((x**0.5)+1), 2):
if x%i == 0:
break
else:
print(x)
hope it helps !
If you are not using a sieve, then the next best are probably wheel methods. A 2-wheel checks for 2 and odd numbers thereafter. A 6-wheel checks for 2, 3 and numbers of the form (6n +/- 1), that is numbers with no factors of 2 or 3. The answer from taoufik A above is a 2-wheel.
I cannot write Python, so here is the pseudocode for a 6-wheel implementation:
function isPrime(x) returns boolean
if (x <= 1) then return false
// A 6-wheel needs separate checks for 2 and 3.
if (x MOD 2 == 0) then return x == 2
if (x MOD 3 == 0) then return x == 3
// Run the wheel for 5, 7, 11, 13, ...
step <- 4
limit <- sqrt(x)
for (i <- 5; i <= limit; i <- i + step) do
if (x MOD i == 0) then return false
step <- (6 - step) // Alternate steps of 2 and 4.
end for
return true
end function
I leave it to you to convert that into Python.
As in
n = 10000
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p
print 'Done'
?

Categories