0
我想解决项目欧拉14和输出总是零。项目欧拉14:输出总是为零
基本想法是n/2
当n
是偶数和3n + 1
当n
是奇数。 然后如果m/2 < n
或m < n
(其中m/2
或m
是先前已经计算了其编号的号码)给出作为迭代存储的迭代次数。 我正在存储以前数字的迭代。
#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
并且相应计算,则为奇数。
请参阅此维基页面,如果修复得当,您可能会得到更多的质量响应。 https://en.wikipedia.org/wiki/Indent_style – ChrisCM
欢迎来到Stack Overflow!我想帮助你,但我不明白你是如何解决问题的。我尝试了一种标准的暴力方法,我能够在不到一秒的时间内得到结果。 https://gist.github.com/moretti/6141287 –
你的代码有点乱(对我来说)你正在重新初始化函数中的p [0-2],该函数应该在数组声明/定义中,其余部分p是未知的未处理!好的意义和位置躲过了我。现在最重要的是你设置了p [num],但从来没有用它来加速搜索,如果if(p [num]!= 0)返回p [num]或count = p [num]没有意愿决定你的功能界面。此外,只有当您将p []数组首先重置为零值时才有效!如果这没有帮助添加评论,我发布代码的答案 – Spektre