0

我正在尝试解决 Project Euler 14 并且输出始终为零。

基本思想是n/2什么时候n是偶数,3n + 1什么时候n是奇数。然后 if m/2 < nor m < n(其中m/2orm是之前已经计算过的数字)给出迭代次数作为存储的迭代次数。我正在存储以前数字的迭代。

#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并相应地计算。

4

1 回答 1

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);
}
于 2015-01-22T16:56:44.907 回答