2013-08-02 75 views
0

我想解決項目歐拉14和輸出總是零。項目歐拉14:輸出總是爲零

基本想法是n/2n是偶數和3n + 1n是奇數。 然後如果m/2 < nm < n(其中m/2m是先前已經計算了其編號的號碼)給出作爲迭代存儲的迭代次數。 我正在存儲以前數字的迭代。

#include<iostream> 
using namespace std; 

bool ok=true; 
unsigned long int p[1000001]; //initialization of array p to store iterations 
unsigned long int q[2]={1,1}; // initialization of two element array to store the max sequence number 
unsigned long int x=0; 

int Colltz(unsigned long int num,unsigned long int count) { // function starts 
    unsigned long int j=num; 
    p[0]=0; //Initial iterations for 1 and 2 
    p[1]=1; // Initial value for 1 
    p[2]=2; // Initial val for 3 
    while(ok) { // while loop 

     if((j%2==0)&&(j/2>num)) { //(to check whether j is available in the array if not it divides it further until j/2<num 
      j=j/2; 
      ++count; 
     } 

     if((j%2==0)&&((j/2)<num)) { // since j/2 the arry should contin the number and the collatz vlue is +1 
      ++count; 
      p[num]=p[j/2]+count; 
      ok=false; 
      break; 
     } 

     if ((j%2)!=0) { //if it is odd 
      j=3*j+1; 
      ++count; 
      Colltz(j,count); 
     } 
     if(j<num) { // if j < num then j is Collatz of j is calculated and added 
      p[num]=p[j]+count; 
      ok=false; 
      break; 
     } 
     if((p[num]>=q[1])) { 
      q[0]=num; // to get the max count 
      q[1]=p[num]; 
     } 
    }// end of while loop 
    return q[1]; 
} 

int main() { 
    unsigned long int i=3; 
    unsigned long int j=0; 
    int counted=1; 

    while(i<6) { 
     j=Colltz(i,counted); 
     ++i; 
    } 
    cout<<j; 
} 

所以基本上我的功能應在數量(本人已初始化count0),然後找出它是否是奇數還是偶數,如果它甚至是否大於n以下,然後按照相應的步驟進行操作,如果是小於n並且相應計算,則爲奇數。

+0

請參閱此維基頁面,如果修復得當,您可能會得到更多的質量響應。 https://en.wikipedia.org/wiki/Indent_style – ChrisCM

+0

歡迎來到Stack Overflow!我想幫助你,但我不明白你是如何解決問題的。我嘗試了一種標準的暴力方法,我能夠在不到一秒的時間內得到結果。 https://gist.github.com/moretti/6141287 –

+0

你的代碼有點亂(對我來說)你正在重新初始化函數中的p [0-2],該函數應該在數組聲明/定義中,其餘部分p是未知的未處理!好的意義和位置躲過了我。現在最重要的是你設置了p [num],但從來沒有用它來加速搜索,如果if(p [num]!= 0)返回p [num]或count = p [num]沒有意願決定你的功能界面。此外,只有當您將p []數組首先重置爲零值時纔有效!如果這沒有幫助添加評論,我發佈代碼的答案 – Spektre

回答

0

你的代碼似乎有點搞砸了!檢查我的解決方案,看看是否有幫助:

#include <stdio.h> 
unsigned long int Collatz(unsigned long int); 

int main() 
{ 
    unsigned long int n,i,bingo; 
    int ChainLen=0; 
    for(i=1;i<=1000000;i++) 
    { 

     if((n=Collatz(i)) > ChainLen) 
     { 
      ChainLen=n; 
      bingo=i; 
     } 

    } 
    printf("\n%lu\n",bingo); 
    return 0; 
} 

unsigned long int Collatz(unsigned long int x) 
{ 
    if(x==1) 
    return 1; 
    if(x%2==0) 
    { 
     return 1 + Collatz(x/2); 
    } 
    else 
    return 1 + Collatz(x * 3 + 1); 
}