30-running-time-and-complexity
Objective
Today we’re learning about running time! Check out the Tutorial tab for learning materials and an instructional video!
Task
A prime is a natural number greater than that has no positive divisors other than and itself. Given a number, , determine and print whether it’s or .
Note: If possible, try to come up with a primality algorithm, or see what sort of optimizations you come up with for an algorithm. Be sure to check out the Editorial after submitting your code!
Input Format
The first line contains an integer, , the number of test cases.
Each of the subsequent lines contains an integer, , to be tested for primality.
Constraints
Output Format
For each test case, print whether is or on a new line.
Sample Input
3
12
5
7
Sample Output
Not prime
Prime
Prime
Explanation
Test Case 0: .
is divisible by numbers other than and itself (i.e.: , , ), so we print on a new line.
Test Case 1: .
is only divisible and itself, so we print on a new line.
Test Case 2: .
is only divisible and itself, so we print on a new line.
Current Buffer (saved locally, editable)
import math
# func 1 is not good! Wast a lots of time,so some cases->Terminated due to timeout :(
def isPrime(n):
if n<1 or n>2*(10**9):
return 0
if n == 1:
return 0
if n == 2:
return 1
for i in range(2,n):
if n%i == 0:
return 0
return 1
# func 2 is good! Wast fewer time! All cases can pass!
def isPrime2(n):
if n<1 or n>2*(10**9):
return 0
if n == 1:
return 0
if n%2 == 0:
return n==2
if n%3 == 0:
return n==3
if n%5 == 0:
return n==5
# think why 2\3\5 is dealed by especially?why 7 isn't dealed by the same way?
for i in range(7,int(math.sqrt(n))+1):
if n%i == 0:
return 0
return 1
T = input().strip()
if int(T)<1 or int(T)>30:
print("T<1 or T>30")
else:
for i in range(int(T)):
n = input().strip()
# flag = isPrime(int(n))
flag = isPrime2(int(n))
if flag:
print("Prime")
else:
print("Not prime")
Congratulations!
You have passed the sample test cases. Click the submit button to run your code against all the test cases.
Testcase 0 Testcase 1
Input (stdin)
3
12
5
7
Your Output (stdout)
Not prime
Prime
Prime
Expected Output
Not prime
Prime
Prime