Search code examples
pythonoopideprimes

python code to find prime or composite number according to given condition


Q) all prime numbers can be written in the form of 6m+1 or 6m-1 for some m>=1. write a program to print "Cannot be decided" if the above property is fulfilled or "Composite number" otherwise.

I can't figure out how to put the given statement into a code. i tried a few codes (such as the one given below) but nothing is striking me. Please help. my code is in the pastebin link because formatting here isn't working properly

https://pastebin.com/sMqT6Eic

n=int(input())
for m in range(1,n):
       
    if n==6*m+1 or n==6*m-1:
        print("Cannot be determined")
    else:
        print("Composite number")
    break

Solution

  • There is no point to having a loop, it's just unnecessary work and it's much less clear. Every prime p greater than 3 must be of the form 6m + 1 or 6m - 1 for some integer m. That's equivalent to saying that p = 1 mod 6 or p = -1 = 5 mod 6. So just make that the test.

    n=int(input('Enter value to test for primality: '))
    
    # assume n > 3
    
    if n % 6 in (1, 5):
        print("Cannot be determined")
    else:
        print("Composite number")