Edit:
1.there was some confusion on the memory limit. I only have 1MB of memory to work with and there is no time limit.
2.the entry number n
specifies the n
digits number that is supposed to be checked. if you enter 3 it will check numbers from 100-999 to see if they are Deletable primes or not
3.it was addressed that division trial for prime numbers takes a long time to process. what algorithm is less memory consuming
4.im using python 3.9
5.i don't measure memory usage. there is an auto-assessment that checks memory usage
6.maximum of n is 8
Question:
I have the assignment to write a script that gets a number n
as input and goes through all n
digit numbers and does the following:
If the number i
is a prime number, cut the right digit and test if it's a prime number again and repeat this until the last digit. If all numbers generated from i
are prime numbers, return i
(for example 797 fits in the description, 797, 79, 7).
Writing the code isn't the problem, there is a memory limit that my script doesn't fulfill.
Here's the code:
import math
def prime(n):
if n == 1:
return 0
for i in range(2, int(math.sqrt(n) + 1)):
if n % i == 0:
return 0
return 1
n = int(input())
def veryprime(i, n):
p = 0
for j in range(n-1, -1, -1):
if j == 0:
if prime(i) == 0:
p = 1
break
del j
else:
if prime(i // (10**j)) == 0:
p=1
break
del j
if p == 0:
print(i)
for i in range(10**(n-1), 10**n):
veryprime(i, n)
What can I do to use less memory?