2013-10-24 42 views
0

我想打開說,我不是很擅長編程,有可能是一個更好的方式做我想做的事情。如果看看那些明顯不好的事情會讓你煩惱,那就繼續前進吧。試圖項目歐拉三

我一直在歐拉項目的第三個問題上做了一個嘗試,那就是「找到600851475143的最大素因子」。首先我做了一些計算數字因子的東西。 (對不起名字,我想不出任何東西。)

#include <iostream> 

using namespace std; 

void Factor (double dFactorer) 
{ 
    long dUpperlimit; 
    dUpperlimit = (int)dFactorer/2; 
    float fnumTouse; 
    fnumTouse = 1; 
    int nCounter; 
    nCounter = 0; 
    while (fnumTouse <= dUpperlimit) 
    { 
     if ((long)dFactorer % (long)fnumTouse == 0) 
     { 
      cout << fnumTouse << endl; 
      fnumTouse++; 
      nCounter++; 
     } 
     else 
     { 
      fnumTouse++; 
     } 
    } 
    cout << dFactorer << endl; 
    cout << "There are " << nCounter + 1 << " factors in this number"; 
} 

int main() 
{ 
    double dNumtofac; 
    cout << "Enter a number to factor: "; 
    cin >> dNumtofac; 
    cout << endl; 
    Factor (dNumtofac); 
    return 0; 
} 

好了,所以,我知道這是一個真正的以次充好的工作,所有的鑄造,我不得不做,使某些事情的工作是什麼。它適用於較小的數字,但大約一億的數字使得它在完全停止之前僅輸出一定數量的因素。我嘗試了問題編號,它的輸出結果是編號本身,並說在這個600851475143中只有一個因素。我想知道它爲什麼這麼說,是否與我使用的變量的限制有關?還有別的嗎?我沒有足夠的知識來解決這個問題。

+0

不知道爲什麼這是downvoted,但我認爲這個問題可能更適合http://codereview.stackexchange.com/或許 – EdChum

+0

@EdChum我不這麼認爲。它有一個特定的問題:它不會產生正確的答案。 – BoBTFish

+0

在32位平臺上,int變量的最大值是2147483647,所以不要期望你的代碼處理更大的數字 – Andrey

回答

0
#include <iostream> 

using namespace std; 

int main() 
{ 
long long n=0; 
//to do: verify that the number is positive and below the limit of long long 
cout <<"The number to factor : "; 
cin >>n; 
long long aux = n%2==0 ? 2 : 1; 
for (long long i=3;i<=n/2;i+=2) 
    if(n%i==0) 
     aux = aux>n/i ? aux : n/i; 
cout<<"Greatest factor = "<<aux; 
return 0; 
} 

當然,你可以通過使得從高到低停止,並在第一次出現因素時停止,從而大大改善這一點。不要忘記驗證n/2是奇數還是偶數。 (沒有測試代碼)。