项目Euler 14:输出始终为零

时间:2013-08-02 15:40:43

标签: c++

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

n/2为偶数时基本构思为n3n + 1为奇数时基本构思为n。 然后,如果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;
}

所以基本上我的函数应该接受数字(我已经将count初始化为0),然后找出它是偶数还是奇数,如果它是否是大于n或更少,然后相应地执行相应步骤,如果奇怪是否小于n并进行相应计算。

1 个答案:

答案 0 :(得分: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);
}