相关疑难解决方法(0)

如何检查数字是否为2的幂

今天我需要一个简单的算法来检查一个数是否是2的幂.

算法需要是:

  1. 简单
  2. 纠正任何ulong价值.

我想出了这个简单的算法:

private bool IsPowerOfTwo(ulong number)
{
    if (number == 0)
        return false;

    for (ulong power = 1; power > 0; power = power << 1)
    {
        // This for loop used shifting for powers of 2, meaning
        // that the value will become 0 after the last shift
        // (from binary 1000...0000 to 0000...0000) then, the 'for'
        // loop will break out.

        if (power == number)
            return true;
        if (power > number)
            return false; …
Run Code Online (Sandbox Code Playgroud)

c# algorithm math

549
推荐指数
13
解决办法
21万
查看次数

检查一个整数是否是另一个整数幂

这是一个采访问题:"给定2个整数x和y,检查x是否是y的整数幂"(例如,对于x = 8和y = 2,答案是"真",对于x = 10和y = 2 "假").

明显的解决方案是:

int n = y; while(n < x) n *= y; return n == x
Run Code Online (Sandbox Code Playgroud)

现在我在考虑如何改进它.

当然,我可以检查一些特殊情况:比如他们xy应该是奇数或偶数,也就是说,我们可以检查的至少显著位xy.但是我想知道我是否可以改进核心算法本身.

algorithm math

29
推荐指数
3
解决办法
2万
查看次数

如何快速评估零集?

这个最近的代码高尔夫职位询问了C中快速实现的可能性(假设n是无符号整数):

if (n==6 || n==8 || n==10 || n==12 || n==14 || n==16 || n==18 || n==20)

一种可能的简化是观察数字a[]={6,8,10,12,14,16,18,20}形成算术级数,因此改变范围然后使用一些按位技巧

if (((n - 6) & 14) + 6 == n)

正如John Bollinger 所回答的那样,实现了更短(可能确实更有效)的实现.

现在我问的是什么是类似优雅(并且希望同样有效)的实现

if (n==3 || n==5 || n==11 || n==29 || n==83 || n==245 || n==731 || n==2189)

提示:这次数字a[k]形成几何级数:a[k]=2+3^k.

我想在一般情况下,不能比排序数字更好a[k],然后进行对数搜索以测试是否n是排序数组的成员.

c c++ sorting performance search

22
推荐指数
3
解决办法
1852
查看次数

确定可以计入素数的下一个最高数字{2,3,5,7}

我想写一个函数,给出一个无符号整数作为输入参数,并返回可以计入素数{2,3,5,7}的下一个最高数字.这是一段简短的代码片段,展示了我想要做的事情.

unsigned int getHigherNumber(unsigned int x)
{
    // obtain the next highest number that can be factored into
    // prime numbers (2, 3, 5, and 7)
    if (~(x % 2 || x % 3 || x % 5 || x % 7))
        return  x;
    else
    {
         // ???
    }  
} // end
Run Code Online (Sandbox Code Playgroud)

此函数的目的是找到应填充数组的零的数量,以确保FFTW(链接)等算法能够以有效的方式运行.给定的链接讨论了该算法对于可以被分解为小素数的长度的输入是最优的.

如对该问题的评论中所建议的,如果FFTW算法是最优的,则看起来仅允许形式为2 ^ a*3 ^ b*5 ^ c*7 ^ d的数字.

c++ modulus

3
推荐指数
1
解决办法
546
查看次数

为什么这个算法对于不是2的幂的整数会失败?

基于这个答案,我在Python 3.x中实现了一个简单的算法,以确定整数n是否是另一个整数的幂base.但是,该算法不会返回正确的结果.链接答案中的代码是:

while (n % 3 == 0) {
    n /= 3;
}
return n == 1;
Run Code Online (Sandbox Code Playgroud)

(注释表明n == 0逻辑上也需要检查).这是我的代码:

def is_power(n: int, base: int) -> bool:
    if n == 0:
        return false
    while (n % base == 0):
        n /= base
    return n == 1
Run Code Online (Sandbox Code Playgroud)

我编写了简单的测试代码来测试某些范围的基数和指数,但它返回的结果是不正确的.测试代码:

for base in range(3, 10):
    print("Base: {0}".format(base))
    for exp in range(30, 40):
        b = is_power(pow(base, exp), base)
        if not(b):
            print("{: <3}: …
Run Code Online (Sandbox Code Playgroud)

python algorithm python-3.x

1
推荐指数
1
解决办法
179
查看次数

标签 统计

algorithm ×3

c++ ×2

math ×2

c ×1

c# ×1

modulus ×1

performance ×1

python ×1

python-3.x ×1

search ×1

sorting ×1