0

For clarification, this is not the same as this question Sieve of Eratosthenes - Finding Primes Python because I don't want to generate Prime Numbers between two numbers but I want to check if a number is a prime number or not.

I made the following code to find whether a number is a prime number or not. Then I heard about the Sieve of Eratosthenes Algorithm which apparently is faster, but I don't know how to write it in the following code?

number1 = int(raw_input("""
Enter any number :- """))
if number1 == 1:
    print "1 is a special case. It is neither a Prime Number nor a Normal Number. Be like 1"
if number1 == 2:
    print number1, "is a Prime Number"
if number1 == 4:
    print "4 is not a Prime Number"
    print "2 times 2 is 4"
if number1 > 1:
    for i in range(2,(number1//2)):
        if number1 % i == 0:
            print number1, "is not a Prime Number"
            print i, "times", (number1/i), "is", number1
            break
    else:
        print number1, "is a Prime Number"
else:
    print "Please type a positive number only"    

Can you guys please help me?

luciferchase
  • 559
  • 1
  • 10
  • 24
  • You can check this question if it helps [https://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python][1] – Anurag A S Feb 24 '19 at 05:20
  • 1
    This is a side issue, but you can put `number1 = int(number1)` after the input and then you don't have to call `int()` throughout the rest of the code. – John Gordon Feb 24 '19 at 05:23

2 Answers2

0

I did this on repl.it. I made it so every time I found a prime, I stored it in a list.

When calculating whether a number is prime, instead of going through all of the numbers leading up to it, I would go through all the numbers in the list.

This emulates what the sieve of eratasthenes would have you do.

Jack Papel
  • 51
  • 2
  • 3
0

The Sieve of Eratosthenes is a method of generating primes. It would therefore replace your code:

for i in range(2,(number1//2)):
    if number1 % i == 0:
        # handle non-prime

with

if number1 in previous_generated_primes:
    # handle non-prime
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • If your question is, instead, "how do I generate primes with the sieve of eratosthenes," then this question is [a dupe of this](https://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python) – Adam Smith Feb 24 '19 at 05:46
  • Can't we apply it to check whether a number is a prime number or not? – luciferchase Feb 24 '19 at 05:58
  • @Lucifer yes, using the method I described above. – Adam Smith Feb 24 '19 at 06:09