有没有办法找到给定整数的素因子数?

问题描述 投票:0回答:1

我正在尝试实现一个函数来分解一个数字,到目前为止我有这个代码:

int * factor(int n) {
  int * vet;
  //
  int p = 2;
  int index = 0;
  while(n > 1) {
    while(n % p != 0) {
      p++;
      index++;
    }
    n = n / p;
    vet[index]++;
  }
  return vet;
}

此函数应返回一个数组,其中包含n数的每个素数因子的幂。像那样:

如果1200 = 2x2x2x2x3x5x5,则1200 = 2 ^ 4 + 3 ^ 1 + 5 ^ 1,因此如果1200是参数,函数应该返回数组{4,1,0,3}。

如果440 = 2x2x2x5x11,那么440 = x ^ 3 + 5 ^ 1 + 11 ^ 1,函数应返回数组{3,0,0,1,0,0,0,0,0,1}

我的问题是关于在vet循环中,在开始形成过程之前,是否存在某种确定while大小的方法。

另外,使用这个结果数组(或上面概念的一些变化),是否有可能为这个数字找到2的幂?例如:

440 = 1x2 ^ 8 + 1x2 ^ 7 + 0x2 ^ 6 + 1x2 ^ 5 + 1x2 ^ 4 + 1x2 ^ 3 + 0x2 ^ 2 + 0x2 ^ 1 + 0x2 ^ 0导致数组{1,1,0,1, 1,1,0,0,0}

1200 = 1x2 ^ 10 + 0x2 ^ 9 + 0x2 ^ 8 + 1x2 ^ 7 + 0x2 ^ 6 + 1x2 ^ 5 + 1x2 ^ 4 + 0x2 ^ 3 + 0x2 ^ 2 + 0x2 ^ 1 + 0x2 ^ 0导致数组{ 1,0,0,1,0,1,1,0,0,0,0}

algorithm prime-factoring
1个回答
0
投票

一个简单的解决方案,是最快的时间:

void getFactors(int n)
{
    while (n%2 == 0)
    {
        n = n/2;
    }

    for (int i = 3; i * i <= n; i = i+2)
    {
        // While i divides n, print i and divide n
        while (n%i == 0)
        {  
            std::cout<<i<<std::endl;
            n = n/i;
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.