Basic-Python-Programs
Basic-Python-Programs copied to clipboard
python code to print all prime numbers
Hey I would like to work on this program. Could you assign it to me?
Hey can you assign me this issue if not completed yet?
All prime numbers in the given range prime.txt
Can you take this one, it will be my first contribution ( make me happy) ` import math num = int(input("Enter last digit upto which you want prime numbers : ")) numbers = [] for i in range(2, num+1): isPrime = True for j in range(2, math.ceil(i**0.5)): if i % j == 0: isPrime = False break if isPrime: numbers.append(i)
print(numbers) `
aman3002's solution is better by far.
You can also check for every number if it's divisible by prior prime numbers. This can be demonstrated in factor trees, where all numbers can be traced down to a prime number, like 2, 3, 5, 7, and so on, unless of course it's a prime number in itself, of which it then can be added to prime numbers list. This list will be used to check for other prime numbers. This is a quick implementation.
def find_prime_numbers(ceiling):
prime_numbers = [2]
for i in range(2, ceiling+1):
#print("i", i)
for j in prime_numbers:
#print("j", j)
#print(f"Checking if {i} is divisible by {j}.")
if i % j == 0:
if i != j:
#print("It is.")
#print(prime_numbers)
#print()
break
#print("They're the same number.")
#print(prime_numbers)
#print()
else:
#print("It is not")
if i not in prime_numbers and j == prime_numbers[-1]:
#print("Appending", i)
prime_numbers.append(i)
#print(prime_numbers)
#print()
return prime_numbers
# Change ceiling, must be inside print() function.
print(find_prime_numbers(100))
This is 100% not optimised as it has O(n^2) time complexity since it has two loops, but it shouldn't be too bad for lower numbers. Commented prints were used for debugging. Some cases like ceiling being 1 will probably not work, and I haven't added any new error handling, so feel free to do that if you'd like.
Prime list in range
Hi everyone! I've optimized the prime number generation code to handle larger numbers more efficiently. This version utilizes the square root of the number for prime checking, which significantly reduces the number of computations needed. Feel free to check it out and contribute further improvements!
import math
n = int(input())
p = []
def isprime(n):
if n > 1:
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
for i in range(n):
if isprime(i):
p.append(i)
print(p)