我正在尝试解决 Project Euler 14 并且输出始终为零。
基本思想是n/2
什么时候n
是偶数,3n + 1
什么时候n
是奇数。然后 if m/2 < n
or m < n
(其中m/2
orm
是之前已经计算过的数字)给出迭代次数作为存储的迭代次数。我正在存储以前数字的迭代。
#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
并相应地计算。