Codility经典算法题之二十九:CountSemiprimes

Task description:

prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.

semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.

You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.

Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.

For example, consider an integer N = 26 and arrays P, Q such that:

P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20

The number of semiprimes within each of these ranges is as follows:

  • (1, 26) is 10,
  • (4, 10) is 4,
  • (16, 20) is 0.

Write a function:

class Solution { public int[] solution(int N, int[] P, int[] Q); }

that, given an integer N and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries.

For example, given an integer N = 26 and arrays P, Q such that:

P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20

the function should return the values [10, 4, 0], as explained above.

Assume that:

  • N is an integer within the range [1..50,000];
  • M is an integer within the range [1..30,000];
  • each element of arrays P, Q is an integer within the range [1..N];
  • P[i] ≤ Q[i].

Complexity:

  • expected worst-case time complexity is O(N*log(log(N))+M);
  • expected worst-case space complexity is O(N+M), beyond input storage (not counting the storage required for input arguments).

Solution:

要求时间复杂度是O(N)我的显然是O(N**3)了,不过正确度测试是百分百

def solution(n,p,q):#1,26 找到1到26之间的半素数 1,4,6  26,10,20
    maxv = max(max(p,q)) #find all the semiprime between 0 and the max integer of these two arrays
    num=[]
    semiprime=[]
    semipq=[]
    result=[]
    for i in range(2,maxv):#find all primes between 2 and maxv
       j=2
       for j in range(2,i):
          if(i%j==0):
             break
       else:
          num.append(i)

    for i in num:  #find all semiprimes between 2 and maxv
        for j in num:
            if i*j not in semiprime:
                semiprime.append(i*j)
    
    for i,j in zip(p,q):
        semipq=[]
        for k in range(i,j+1):
            if k in semiprime :
                if k not in semipq:
                    semipq.append(k)
        result.append(len(semipq))
    return result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

科技改变未来

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值