【问题标题】:Find number of special numbers in a given range查找给定范围内的特殊数字的数量
【发布时间】:2014-04-16 04:51:34
【问题描述】:

我无法降低这个问题的复杂性。请提供一些更好的方法。

是否有我不知道的数学公式,或者可以用更好的方法来完成?

Problem Link

说明:

 A special number is not divisible by any number of the form Z*Z where (Z>1).

问题:求给定范围内特殊数字的个数。

Integer Limit:10^9

我是这样做的:

    import math
    def special(x):
        flag=1
        i=2
        if(x==0 or x==1 or x==2):
            return 1
        while(i*i <= x):               //This is the best i can think to limit the numbers.
            if(x%(i*i)==0):
                flag=0
                break
            i=i+1
        return flag

    t=int(raw_input())
    while(t):
        x,y=map(int,raw_input().split())
        count=0
        for i in xrange(x,y+1):
            if(special(i)):
                count+=1
        print(count)
        t=t-1

【问题讨论】:

标签: python algorithm numbers


【解决方案1】:

special(x) 中,您只需遍历小于或等于 sqrt(x) 的素数。 所以我会预先计算一个素数列表 (Fastest way to list all primes below N)。

【讨论】:

  • 为什么只有素数?假设数字是 36,那么它可以被 6*6 整除。所以在特殊函数中,我们需要检查 6 是否不是素数。
猜你喜欢
  • 2020-10-03
  • 2014-04-27
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多