【hackerrank】-Day 25: Running Time and Complexity

24 篇文章 0 订阅
24 篇文章 0 订阅

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值