c – 计算具有三个不同素因子的数字

numbers.txt中有1000个数字,每个数字2到9位,每个数字都在一个单独的行中.练习是计算有多少数字,满足条件:当分解时,这个数字恰好有3个不同的素因子,它们可以出现几次,它们都是偶数.

例如
 105 – 因素:3,5,7 – 是的,
1287 – 因素:3,3,11,13 – 是的,

1157625 – 因素:3,3,3,5,5,5,7,7,7 – 是的,

55 – 因素:5,11 – NO.

#include <iostream>
#include <fstream>
using namespace std;
int number, threefnumbers=0;
int main()
{
  ifstream file("numbers.txt");
  ofstream outputf("results.txt");
  int count_factors;
  while (file >> number)
  {
    count_factors=0;
    int factor=3;
    if (number%2!=0)
    {
       while (number>1)
       {
        if (number%factor==0)
          count_factors++;
        while (number%factor==0)
        {
          number=number/factor;
        }
        factor+=2;
       }
       if (count_factors==3) threefnumbers++;
     }
  }

  outputf << "59.1) " << endl << threefnumbers;

  file.close();
  outputf.close();
  return 0;
}

我从numbers.txt中知道,有许多数字符合条件,但程序只返回1.为什么会这样?

最佳答案 您的代码忽略了2是素数的事实.您需要检查读入的数字是否可以减少2.您可以使用以下内容来执行此操作:

while(read number)
{
    int factor_count = 0;
    // check 2 by itself
    if (number % 2 == 0)
    {
        factor_count++;
        while(number % 2 == 0)
            number /= 2;
    }
    for (int factor = 3; factor < number; factor += 2)
    {
        if (number % factor == 0)
        {
            factor_count++;
            while(number % factor == 0)
                number /= factor;
        }
    }
    if(factor_count == 3)
        do something
}

通过在文件中创建可能达到最大数量的素数列表,可以使整个事情更有效率,在本例中为999,999,999.然后你可以遍历那个素数列表,直到你用完素因子.这看起来像

std::vector<int> primes = get_prime_list(999999999);  
// returns a list of all prime numbers less than the number passed in.
// leaving it to you to implement but a Sieve of Eratosthenes should work well
while(read number)
{
    int factor_count = 0;
    for(auto e : primes)
    {
        if (number % e == 0)
        {
            factor_count++;
            while(number % e == 0)
                number /= e;
        }
        if (number == 1) // number is fully factorized
            break;
    }
    if(factor_count == 3)
        do something
}
点赞