Home > database >  Have some doubts in this python program (PRIME or NOT)
Have some doubts in this python program (PRIME or NOT)

Time:11-20

So, I wrote a code to find if a number is PRIME or NOT...

I wrote it in 2 different ways, they are almost same but I just had a doubt. So here it is:

1st code:

num = int(input("Enter the number: "))
lim = num//2   1
for i in range(2,lim):
    if num % i == 0:
        print("Prime!")
        break
else:
    print("Not Prime!")

2nd Code:

num = int(input("Enter the number: "))
for i in range(2,num):
    if num % i == 0:
        print("Prime!")
        break
else:
    print("Not Prime!")

The 1st code takes the input(num) and according to the input sets a limit(which is the half number 1) and then checks if the num is divisible by all the numbers in range (2 to lim)

The second one is same but instead of setting a limit it just checks all numbers lower than the input, which means it has to do a little more work...

Now both of these are almost same, the only difference is I saved a line in 2nd one and output efficiency is also better!

Which code would you want me to prefer/

also if this code has any problems, pointing them out would be helpful! Thanks :)

CodePudding user response:

The logic of the solution is wrong. You gave to switch the "Prime" and "Not Prime" tags. Like follows;

num = int(input("Enter the number: "))
lim = num//2   1
for i in range(2,lim):
    if num % i == 0:
        print("Not Prime!")
        break
else:
    print("Prime!")

The solution 1 is more efficient because you do not need to do extra computation to check num//2 1. So it is preferable.

CodePudding user response:

num = int(input("Enter the number: "))
lim = num//2   1
isprime = True
for i in range(2,lim):
    if num % i == 0:
        isprime = False
        break

if isprime:
    print("Prime!")
else:
    print("Not prime!")
  • Related