Home > Net >  python code to find prime or composite number according to given condition
python code to find prime or composite number according to given condition

Time:10-16

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

CodePudding user response:

There is indentation errors and also remove the ''' near the declaration of n variable. Break the loop when the condition is satisfied not outside the if statement. It will check only for m=1 and break the loop. Take a new variable that will update its value when the condition is satisfied and the loop breaks. If the variable is updated, it is prime and if variable is not updated, the condition was never satisfied and it is composite. Edited code:

n=int(input())
m=int()
f=0           #new variable
for m in range(1,n):
    if n==6*m 1 or n==6*m-1:
        f=1     #update the variable when condition satisfied
        break   #break the loop
    else:
        continue
if f==1:       #updated value when condition satisfied
    print("Cannot be determined")
else:
    print ("Composite")

CodePudding user response:

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")
  • Related