2016-05-12 53 views
4

number.txt中有1000個數字,每個數字爲2到9位數字,每個數字在一個單獨的行中。該練習計算了有多少數字,滿足條件:分解時,這個數字恰好有3個不同的素數因子,它們可以出現多次,而且都是偶數。計算具有三種不同素數因子的數字

例如 - 因素:3,5,7 - YES, - 因素:3,3,11,13 - YES,

- 因素:3, 3,3,5,5,5,7,7,7 - 是,

- 因子:5,11 -

#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.爲什麼這樣?

+1

「他們都是偶數」。你的例子中的數字都不是! – CinCout

+0

不可能有偶數。素數總是很奇怪。 – AhmadWabbi

+1

@ A.Wabbi 2是一個素數 – NathanOliver

回答

2

您的代碼忽略了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 
}