Belphegor prime number problem with Python - python

I have seen a video about Belphegor prime numbers. The definition of a Belphegor prime is one such that in the expression (10^(n+3)+666)*(10^(n+1)+1) is prime for n being a positive integer.
I tried making a Python program that would determine whether an input number n will produce a prime number in the expression mentioned before but my code said that for all n in the expression would be prime which is not true and it said it indefinitely.
My code:
n = int(input("Enter a positive number n: "))
x =(10**(n+3)+666)*10**(n+1)+1
for i in range(2,x - 1):
if x % i == 0:
print("Composite")
else:
print("Belphegor prime")
Please help me fix this error!

Your problem is that your code prints out either Composite or Prime on every iteration through the loop. Instead, you need to assume the number is prime and if at any time the test fails, set a flag to false; then use the state of the flag at the end of the loop to determine if the number is actually prime:
from math import sqrt
n = int(input("Enter a positive number n: "))
x =(10**(n+3)+666)*(10**(n+1)+1)
p = True
for i in range(2,int(sqrt(x))+1):
if x % i == 0:
p = False
break
if p:
print("Belphegor prime")
else:
print("Composite")
Note you can shorten your loop by only iterating as far as sqrt(x) as any number greater than sqrt(x) which is a divisor of x will have a matching divisor less than sqrt(x).
Note also that as #LeoE pointed out in the comments to your question, you are missing some () in your computation of x.

Related

Python code that creates list of prime numbers

Trying to create a list of prime numbers in a fixed range. This is producing non-sensical list but the code makes sense to me.
for number in range(2,100,2):
k = 1
while k*k < number:
k += 2
if number % k == 0:
break
else:
print(number)
there are several bugs in your code.
first, you don't check its divisibility by even numbers, any even number to be exact (including 2)! if it is meant as an optimization approach, make it more generic by not checking the numbers who are known already not to be prime. its called the sieve of eratosthenes
another, is that you don't check the divisibility if n is a square root of a prime number as you pass the k*k = number case.
this is my implementation for a naive n * sqrt(n):
for number in range(2,100):
prime, divisor = True, 2
while prime and divisor ** 2 <= number:
if number % divisor == 0:
prime = False
divisor += 1
if (prime):
print(number)
Change like this:
for number in range(2, 101):
for k in range(2, number):
if (number % k) == 0:
break
else:
print(number)
for number in range(1,100):
counter=0
for test in range(1,number+1):
if number%test==0:
counter=counter+1
if counter<=2:
print(number)

Find prime numbers less than or equal to the number the user has entered with loops. How do I do that?

With this code, I only get to test if the number the user entered is prime or not.
How do I add another loop to my original code in order to find all the prime numbers less than or equal to the number the user has entered?
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
You can'not print both in one loop, you can do one thing add a loop above your current loop and display each number like this :
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
#your current code ends here
for j in range(2, num + 1):
# prime numbers are greater than 1
for i in range(2, j):
if (j % i) == 0:
break
else:
print(j)
Your code only check the number entered is prime or not , but you questioned about to get prime numbers from 2 to n (n = number entered by user) for this you run below code with the help of flag bit it will little bit easy for you. i hope it will help you.
Try This i run this code It will Surely help you to find your answer it work in python 3.0 or above
num = int(input("Enter The Number"))
if num > 1:
num = num+1
list = []
for j in range (2,num,1):
flag = 0
for i in range (2,int(j/2)+1,1):
if(j%i)== 0:
flag = 1
break
if flag==0:
list.append(j)
print(list)
else:
print("Enter Number Greater Than 1")
Aside from small things (unused boolean variable) your prime test is also super inefficient.
Let's go through this step by step.
First: To test if a number is prime, you don't need to check all integers up to the number for divisors. Actually, going up to sqrt(num) turns out to be sufficient. We can write a one-liner function to find out if a number is prime like so:
from numpy import sqrt
def is_prime(n):
return n > 1 and all(n%i for i in range(2,int(sqrt(n))+1))
range(2,some_num) gives an iterator through all numbers from 2 up to some_num-1and the all() function checks if the statement n%i is true everywhere in that iterator and returns a boolean. If you can guarantee to never pass even numbers you can start the range from 3 (of course with the loss of generality). Even if you don't want to use that function, it's cleaner to separate the functionality into a different function, because in a loop of numbers up to your input you will probably have to check each number for being prime separately anyways.
Second: From here, finding all primes smaller or equal than your input should be pretty easy.
num = int(input("Enter a number:"))
assert num>0, "Please provide a positive integer" # stops with an assertion error if num<=0
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2):
if is_prime(x):
prime_lst.append(x)
The list prime_lst will contain all your sought after prime numbers. I start the loop from 1 such that I can loop through only the odd numbers, even numbers are divisible by two. So this way none of the numbers will be divisible by two. Unfortunately this requires me to check if the number itself may be 2, which is a prime. By the twin-prime conjecture we can not simplify this range further without knowing about the input.
Finally: If you really want to find the primes in one loop, change your loop to something along the lines of:
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2): # outer loop
for i in range(3,int(sqrt(x))+1): # inner loop for check if x is prime
if x%i == 0:
break # breaks the inner loop, number is not prime
else:
prime_lst.append(x)
Edit: Just saw that the second answer here has a good explanation (and an even better way) of writing the one-liner for finding out if a number is prime.

Python Script Not Finishing

I am trying to run my code to try to solve euler problem number 10. I am very new to python and my code has been going very slowly and in this case never ending. Any help would be appreciated. Thank you.
primes = [2]
number = 2
y=1
while y <=1:
for i in primes:
if number % i == 0:
break
else:
if i == primes[-1]:
primes.append(number)
if (primes[-1]) >= 2000000:
del primes[-1]
y += 2
number+=1
print(sum(primes))
SPOILER ALERT: the following contains the answer to question 10 in Project Euler.
Your problem is that your code take too long to run, that is because it is checking too many thing and will take too long to work. In PE question you usually have to think of a trick to get your program to get the result fast enough. In this case you need to understand why there is no need to check weather a prime is divisible by a prime that is bigger the the square root of the number.
If a number x was divisible by a prime number p that is bigger than the square root of x, that would mean that there is a natural number n that is n = x/p, if p is bigger than the square root of x then n is smaller than the square root of x (think about why this is true). That means that we would find that the number x is also divisible by the number n that is smaller than the square root of x. That means we would have already found that x is divisible by n (or a prime factor of n) when we were checking all the numbers that are smaller than the square root of x, therefor there is no need to check any number bigger then the square root of a number is order to know if it is prime Q.E.D .
This way you can save A LOT of computations. the following is a python program that implements this idea:
import math
primes = [2]
is_prime = True
# loop over all the ODD numbers from 3 to 2,000,000 (no need to check even numbers)
for number in xrange(3, 2000000 + 1, 2):
sqrt = math.sqrt(number)
# loop over all the primes we have so far
for prime in primes:
# if the number we are checking is divisible by a prime it is not prime and we can move on to the next number
if number % prime == 0:
# we set this value to false so that when we finish the loop we will be able to know if the number is prime or not
is_prime = False
break
# this line is where the clever part is, if we already checked `all the primes that are smaller than square root of x, and we did not find any primes that our number is divisible by, then we will not find any primes higher than the square root of the number that the number is divisible by`
if prime > sqrt:
break
if is_prime:
primes.append(number)
else:
is_prime = True
# we are done, print the answer
print sum(primes)
As much as I appreciate the detailed answer by #DonatPants, I believe that solution is too complicated. First, we don't need to calculate sqrt() when the simpler square will do (I.e. square both sides of the equation.) Second the order of tests seems backward, why check prime > sqrt after if number % prime == 0? If prime > sqrt, you don't need the other test. And what's with that boolean? My simpler approach to this problem:
primes = [2]
for number in range(3, 2000000 + 1, 2): # only test odd numbers
for prime in primes:
if prime * prime > number: # we're past sqrt, a prime!
primes.append(number)
break
if number % prime == 0: # a composite
break
print(sum(primes))
Redundantly computing prime * prime is an inefficiency. It doesn't make any difference for this range of numbers but if needed, you can keep a separate array of squares, enumerate the primes and use the index generated to access the square, which you save when you save the prime. Squaring just the primes is cheaper than square rooting all the numbers:
primes = [2]
squares = [4]
for number in range(3, 2000000 + 1, 2):
for index, prime in enumerate(primes):
if squares[index] > number:
primes.append(number)
squares.append(number * number)
break
if number % prime == 0:
break
print(sum(primes))
We're wasting space to avoid wasting time. But again, for this range of numbers, it's not worth it.

Prime number finder including 2 multiple times

This program makes a list of all prime numbers less than or equal to a given input.
Then it prints the list.
I can't understand why it includes the number 2. When I first designed the program, I initialized the list with primes = [2] because I thought, since 2 % 2 == 0,
if n % x == 0:
is_prime = False
will set is_prime to False. However, that doesn't seem to be the case.
I'm sure there is something going on with the logic of my range() in the for loops that I just don't understand.
I guess my question is: Why is 2 included in the list of primes every time?
import math
limit = int(input("Enter a positive integer greater than 1: "))
while limit < 2:
limit = int(input("Error. Please enter a positive integer greater than 1: "))
primes = []
#Check all numbers n <= limit for primeness
for n in range (2, limit + 1):
square_root = int(math.sqrt(n))
is_prime = True
for x in range(2, (square_root + 1)):
if n % x == 0:
is_prime = False
if is_prime:
primes.append(n)
#print all the primes
print("The primes less than or equal to", limit, "are:")
for num in primes:
print(num)
Because you don't enter the second for-loop when you test for n=2 and therefore you don't set is_prime = False.
# Simplified test case:
x = 2
for idx in range(2, int(math.sqrt(x))+1):
print(idx)
This doesn't print anything because range is in this case: range(2, 2) and therefore has zero-length.
Note that your approach is not really efficient because:
you test each number by all possible divisors even if you already found out it's not a prime.
you don't exclude multiples of primes in your tests: if 2 is a prime, every multiple of 2 can't be prime, etc.
There are really great functions for finding prime numbers mentioned in Fastest way to list all primes below N - so I won't go into that. But if you're interested in improvements you might want to take a look.

Finding a prime number

The problem is that you need to find the prime number after the number input, or if the number input is prime, return that. It works fine. It's just not working when the input is print(brute_prime(1000)). It returns 1001 not 1009. The full code is this:
def brute_prime(n):
for i in range(2, int(n**(0.5))):
if n % i == 0:
n += 1
else:
return n
As Barmar suggests, you need to restart the loop each time you increment n. Your range also ends earlier than it should, as a range stops just before the second argument.
def brute_prime(n):
while True:
for i in range(2, int(n**(0.5)) + 1):
if n % i == 0:
break
else:
return n
n = n+1
remember 2 is a prime number. again you can just check the division by 2 and skip all the even number division
def brute_prime(n):
while True:
if n==2:return n
elif n%2 ==0 or any(n % i==0 for i in range(3, int(n**(0.5)+1),2)):
n += 1
else:
return n
You're not restarting the for i loop when you discover that a number is not prime and go to the next number. This has two problems: you don't check whether the next number is a multiple of any of the factors that you checked earlier, and you also don't increase the end of the range to int(n ** 0.5) with the new value of n.
def brute_prime(n):
while true:
prime = true
for i in range(2, int(n ** 0.5)+1):
if n % i == 0:
prime = false
break
if prime:
return n
n += 1
break will exit the for loop, and while true: will restart it after n has been incremented.
as mention by Chris Martin the wise solution is define a isPrime function separately and use it to get your desire number.
for example like this
def isPrime(n):
#put here your favorite primality test
from itertools import count
def nextPrime(n):
if isPrime(n):
return n
n += 1 if n%2==0 else 2
for x in count(n,2):
if isPrime(x):
return x
if the given number is not prime, with n += 1 if n%2==0 else 2 it move to the next odd number and with count check every odd number from that point forward.
for isPrime trial division is fine for small numbers, but if you want to use it with bigger numbers I recommend the Miller-Rabin test (deterministic version) or the Baille-PSW test. You can find a python implementation of both version of the Miller test here: http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Python

Categories