SPOJ Prime Generator - python

I guess this isn't the best question in the world, but I can't seem to figure why on earth this code:
def isprime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
for divisor in range(3, int(num ** 0.5) + 1, 2):
if num % divisor == 0:
return False
return True
def case(mini, maxi):
for i in range(mini, maxi + 1):
if isprime(i):
print(i)
test = [line.split() for line in input().split("\n")[1:]]
for line in test:
mini, maxi = [int(num) for num in line]
case(mini, maxi)
print()
does not satisfy SPOJ Question 2?? The prime tester has worked well for me before, and the code works on the example inputs.

Related

Syntax error in python code to find Prime-factors. Id appreciate if someone could help me

I have been getting a syntax error with code which does prime-factorization
The is this Code
from sys import argv
from os import system, get_terminal_size
from math import sqrt
number = int(argv[1])
width = get_terminal_size().columns
prime_numbers = []
prime_factors = []
_ = system('clear')
print()
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if is_prime(number):
print(f"It is a prime number \nIts only factors are 1 and itself \n1, {number}")
exit()
x = len(str(number))
for i in range(2, int(sqrt(number))):
if is_prime(i):
prime_numbers.append(i)
#print(f"found ")
#print(prime_numbers)
i = 0
while True:
if (number % prime_numbers[i] != 0):
i += 1
continue
prime_factors.append(prime_numbers[i])
print("%2d | %3d".center(width) % (prime_numbers[i], number))
print("_________".center(width))
number /= prime_numbers[i]
if number == 1:
break
print("1".center(width))
print("Answer ")
i = len(prime_factors)
j = 1
for k in prime_factors:
if j == i:
print(k)
break
print(f"{k}", end=" X ")
j += 1
This works for small numbers , less than 4 or 5 digits but gives an index error for bigger ones.
If I remove the sqrt function on line 24 it starts taking too long.
The errors look like this
Traceback (most recent call last):
File "prime-factor.py", line 33, in <module>
if (number % prime_numbers[i] != 0):
IndexError: list index out of range
real 0m0.049s
user 0m0.030s
sys 0m0.014s
(base) Souravs-MacBook-Pro-5:Fun-Math-Algorithms aahaans$ time python3 prime-factor.py 145647
I am unable to resolve this issue, Id appreciate it if you could help me.
No need to rebuild what's already available primePy
from primePy import primes
primes.factors(101463649)
output
[7, 23, 73, 89, 97]
There are two basic issues with the code. One with the for loop for prime numbers, you have to check until int(sqrt(number))+1. And, in the while loop after that, you have to break when the number is below sqrt of the original number, for which another variable should be used. The corrected code is:
from sys import argv
from os import system, get_terminal_size
from math import sqrt
number = int(argv[1])
width = get_terminal_size().columns
prime_numbers = []
prime_factors = []
_ = system('clear')
print()
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if is_prime(number):
print(f"It is a prime number \nIts only factors are 1 and itself \n1, {number}")
exit()
x = len(str(number))
limit = int(sqrt(number))
for i in range(2, limit+1):
if is_prime(i):
prime_numbers.append(i)
i = 0
while True:
if i == len(prime_numbers)-1:
# prime_factors.append(int(number))
break
if (number % prime_numbers[i] != 0):
i += 1
continue
prime_factors.append(prime_numbers[i])
print("%2d | %3d".center(width) % (prime_numbers[i], number))
print("_________".center(width))
number /= prime_numbers[i]
prime_factors.append(int(number))
print("%2d | %3d".center(width) % (number, number))
print("_________".center(width))
print("1".center(width))
print("Answer ")
i = len(prime_factors)
j = 1
for k in prime_factors:
if j == i:
print(k)
break
print(f"{k}", end=" X ")
j += 1
If my explanation wasn't clear, look at the changes in the code.
I wrote a small number factorization engine that can factor 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
#print (s, x, prime, xx)
return prime
Factor:
In [219]: LLL(10142789312725007)
Out[219]: 100711423
from https://stackoverflow.com/questions/4078902/cracking-short-rsa-keys
I also made Alpertons ECM SIQs engine work in python if you want factorization at that (over 60 digits level): https://github.com/oppressionslayer/primalitytest

Fastest way to find prime in intervals

I tried searching StackOverflow and some other sources to find the fastest way to get a prime number within some interval but I didn't find any efficient way, so here is my code:
def prime(lower,upper):
prime_num = []
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prime_num.append(num)
return prime_num
Can I make this more efficient?
I tried finding my answer in Fastest way to find prime number but I didn't find prime numbers in intervals.
I wrote an equation based prime finder using MillerRabin, it's not as fast as a next_prime finder that sieves, but it can create large primes and you get the equation it used to do it. Here is an example. Following that is the code:
In [5]: random_powers_of_2_prime_finder(1700)
Out[5]: 'pow_mod_p2(27667926810353357467837030512965232809390030031226210665153053230366733641224969190749433786036367429621811172950201894317760707656743515868441833458231399831181835090133016121983538940390210139495308488162621251038899539040754356082290519897317296011451440743372490592978807226034368488897495284627000283052473128881567140583900869955672587100845212926471955871127908735971483320243645947895142869961737653915035227117609878654364103786076604155505752302208115738401922695154233285466309546195881192879100630465, 2**1700-1, 2**1700) = 39813813626508820802866840332930483915032503127272745949035409006826553224524022617054655998698265075307606470641844262425466307284799062400415723706121978318083341480570093257346685775812379517688088750320304825524129104843315625728552273405257012724890746036676690819264523213918417013254746343166475026521678315406258681897811019418959153156539529686266438553210337341886173951710073382062000738529177807356144889399957163774682298839265163964939160419147731528735814055956971057054406988006642001090729179713'
or use to get the answer directly:
In [6]: random_powers_of_2_prime_finder(1700, withstats=False)
Out[6]: 4294700745548823167814331026002277003506280507463037204789057278997393231742311262730598677178338843033513290622514923311878829768955491790776416394211091580729947152858233850115018443160652214481910152534141980349815095067950295723412327595876094583434338271661005996561619688026571936782640346943257209115949079332605276629723961466102207851395372367417030036395877110498443231648303290010952093560918409759519145163112934517372716658602133001390012193450373443470282242835941058763834226551786349290424923951
The code:
import random
import math
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 ltrailing(N):
return len(str(bin(N))) - len(str(bin(N)).rstrip('0'))
def pow_mod_p2(x, y, z):
"4-5 times faster than pow for powers of 2"
number = 1
while y:
if y & 1:
number = modular_powerxz(number * x, z)
y >>= 1
x = modular_powerxz(x * x, z)
return number
def modular_powerxz(num, z, bitlength=1, offset=0):
xpowers = 1<<(z.bit_length()-bitlength)
if ((num+1) & (xpowers-1)) == 0:
return ( num & ( xpowers -bitlength)) + 2
elif offset == -1:
return ( num & ( xpowers -bitlength)) + 1
elif offset == 0:
return ( num & ( xpowers -bitlength))
elif offset == 1:
return ( num & ( xpowers -bitlength)) - 1
elif offset == 2:
return ( num & ( xpowers -bitlength)) - 2
def MillerRabin(N, primetest, iterx, powx, withstats=False):
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
PRIMES=list(primes_sieve2(1000000))
def mr_isprime(N, withstats=False):
if N == 2:
return True
if N % 2 == 0:
return False
if N < 2:
return False
if N in PRIMES:
return True
for xx in PRIMES:
if N % xx == 0:
return False
iterx = ltrailing(N - 1)
k = pow_mod_p2(N, (1<<N.bit_length())-1, 1<<N.bit_length()) - 1
t = N >> iterx
tests = [k+1, k+2, k, k-2, k-1]
for primetest in tests:
if primetest >= N:
primetest %= N
if primetest >= 2:
if MillerRabin(N, primetest, iterx, t, withstats) == False:
return False
return True
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def random_powers_of_2_prime_finder(powersnumber, primeanswer=False, withstats=True):
while True:
randnum = random.randrange((1<<(powersnumber-1))-1, (1<<powersnumber)-1,2)
while lars_last_modulus_powers_of_two(randnum) == 2 and mr_isprime(randnum//2) == False:
randnum = random.randrange((1<<(powersnumber-1))-1, (1<<powersnumber)-1,2)
answer = randnum//2
# This option makes the finding of a prime much longer, i would suggest not using it as
# the whole point is a prime answer.
if primeanswer == True:
if mr_isprime(answer) == False:
continue
powers2find = pow_mod_p2(answer, (1<<powersnumber)-1, 1<<powersnumber)
if mr_isprime(powers2find) == True:
break
else:
continue
if withstats == False:
return powers2find
elif withstats == True:
return f"pow_mod_p2({answer}, 2**{powersnumber}-1, 2**{powersnumber}) = {powers2find}"
return powers2find
def nextprime(N):
N+=2
while not mr_isprime(N):
N+=2
return N
def get_primes(lower, upper):
lower = lower|1
upper = upper|1
vv = []
if mr_isprime(lower):
vv.append(lower)
else:
vv=[nextprime(lower)]
while vv[-1] < upper:
vv.append(nextprime(vv[-1]))
return vv
Here is an example like yours:
In [1538]: cc = get_primes(1009732533765201, 1009732533767201)
In [1539]: print(cc)
[1009732533765251, 1009732533765281, 1009732533765289, 1009732533765301, 1009732533765341, 1009732533765379, 1009732533765481, 1009732533765493, 1009732533765509, 1009732533765521, 1009732533765539, 1009732533765547, 1009732533765559, 1009732533765589, 1009732533765623, 1009732533765749, 1009732533765751, 1009732533765757, 1009732533765773, 1009732533765821, 1009732533765859, 1009732533765889, 1009732533765899, 1009732533765929, 1009732533765947, 1009732533766063, 1009732533766069, 1009732533766079, 1009732533766093, 1009732533766109, 1009732533766189, 1009732533766211, 1009732533766249, 1009732533766283, 1009732533766337, 1009732533766343, 1009732533766421, 1009732533766427, 1009732533766457, 1009732533766531, 1009732533766631, 1009732533766643, 1009732533766667, 1009732533766703, 1009732533766727, 1009732533766751, 1009732533766763, 1009732533766807, 1009732533766811, 1009732533766829, 1009732533766843, 1009732533766877, 1009732533766909, 1009732533766933, 1009732533766937, 1009732533766973, 1009732533767029, 1009732533767039, 1009732533767093, 1009732533767101, 1009732533767147, 1009732533767159, 1009732533767161, 1009732533767183, 1009732533767197, 1009732533767233]
Yes. In general, use:
Sieve of Eratosthenes
Miller-Rabin Primality Test
Other options include trying a compiled language, like C++, but I think that isn't what you're looking for, since you've asked about Python.
Yes, you can make it more efficient. As has been mentioned, for very large numbers use Miller-Rabin. For smaller ranges use the Sieve of Eratosthenes. However, apart from that, your prime checker code is very inefficient.
2 is the only even prime number, which can save you doing half the work you do.
You only need to check up to the square root of the number you are testing. In any pair of factors: f and n/f, one is guaranteed to be less then or equal to the square root of the number being tested. Once you find a factor then the number is composite.
My Python is not good, so this is in pseudocode:
isPrime(num)
// Negatives, 0, 1 are not prime.
if (num < 2) return false
// Even numbers: 2 is the only even prime.
if (num % 2 == 0) return (num == 2)
// Odd numbers have only odd factors.
limit <- 1 + sqrt(num)
for (i <- 3 to limit step 2)
if (num % i == 0) return false
// No factors found so num is prime
return true
end isPrime

Python - function returns true when a given number is a prime number or else false

Hi I'm a beginner and I'm stuck on this question that wants me to use only while loop to solve. The question wants me to write a function that returns True when the given number is a prime number and it returns False if the given number is not a prime number.
My code so far:
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
The problem I have is I think my code displays the correct output for numbers 4 and above and it returns 'None' for 1, 2, and 3. I've debugged it and I think the problem is the while loop condition. But I don't know how to fix it. I would appreciate it if any of you pros can help me out!
edit:
I changed the while condition but 1 still returns None.. and 2 returns False when it's supposed to return True
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
You could hard-code these 3 cases, in case you dont want to use sqrt:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
Output:
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
Want to get really fancy? Make a Sieve of Eratosthenes:
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
If you want to impress your lesson teacher you can show him a fast probabilistic prime number isprime for numbers larger than 2**50. I haven't found any errors in it after weeks of cpu time stress testing it on a 6 core AMD:
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)

How do i check if the number is semi prime

def is_prime(num):
if num > 1:
for i in range(2,num):
return False if (num % i) == 0:
if (num % i) == 0:
return False
return True if prime
else:
return True
return False if not prime
else:
return False
def is_semiprime():
n = int(input("Enter a number to find out if its semiprime or not\n>>> "))
for d1 in range(2, int(n**.5)):
if n % d1 == 0:
d2 = int(n / d1)
is_prime(d1) and is_prime(d2) go through and don't tell me there true or false they just send blank lines.
return is_prime(d1) and is_prime(d2)
return False
is_semiprime()
when it Returns is_prime(d1) and is_prime(d2) if they are both True then return True
A semi-prime number is a number that's the product of two prime numbers. So the algorithm is simple:
Find one divisor of the number, call it d1.
Divide the number by d1 to get a second divisor, d2.
Test whether both d1 and d2 are prime. If they are, then the original number is semi-prime.
Code:
def is_semiprime(n):
for d1 in range(2, int(n**.5)+1):
if n % d1 == 0:
d2 = n / d1
return is_prime(d1) and is_prime(d2)
return False
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
def ask_semiprime():
num = int(input("What number would you like to check?"))
if is_semiprime(num):
print(num, " is semiprime")
else:
print(num, " is not semiprime")
ask_semiprime()
I copied the is_prime function from isPrime Function for Python Language
number=int(input())
s=number
x=[]
for i in range(2,number+1):
if s%i==0:
x.append(i)
s=s//I
if s==i or (i>s and s!=1):
x.append(s)
if len(x)==2:
print(f"{number} is a semiprime number because it is the product of Tow primes: ",end="")
else:
print(f"{number} is not a semiprime number because it is the product of {len(x)} primes: ",end="")
for i in x:
if i==x[-1]:
print(i)
else:
print(str(i)+"*",end="")
def check_prime(n): #for checking wheather prime or not
if n > 1:
if n == 2: return True
for i in range(2,n):
if n % i == 0:
return False
break
return True
return False
def primeproduct(m): #for checking wheather prime product or not
if m >= 0:
for i in range(1,m):
if m%i == 0 and check_prime(i) and check_prime(m//i):
return True
break
return False
this may help

The "3n+1" Programming Challenge in Pythonallenge

I'm a Python beginner. I'm trying to solve the 3n+1 problem on UVa Online Judge. The program worked fine with the input files. However, I submitted several times but still got Runtime error.
import sys
def compute(i, j):
maxCycleLength = 1
if i <= j/2:
k = j/2+1
else:
k = i
for n in range(k, j+1):
num = n
cycleLength = 1
while (num != 1):
if num%2 != 0:
num = 3*num+1
else:
num = num/2
cycleLength += 1
if cycleLength > maxCycleLength:
maxCycleLength = cycleLength
return maxCycleLength
while True:
nums = sorted(int(x) for x in next(sys.stdin).split())
m = compute(nums[0], nums[1])
print("{} {} {}\n".format(nums[0], nums[1], m))

Categories

Resources