C++ Project Euler 14:输出始终为零
我试图解决Euler 14项目,结果总是零 基本思想是当C++ Project Euler 14:输出始终为零,c++,C++,我试图解决Euler 14项目,结果总是零 基本思想是当n为偶数时n/2,当n为奇数时3n+1。 然后,如果m/2
n
为偶数时n/2
,当n
为奇数时3n+1
。
然后,如果m/2
或m
(其中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;
}
#包括
使用名称空间std;
bool ok=true;
无符号长整数p[1000001]//初始化数组p以存储迭代
无符号长整型q[2]={1,1};//初始化两元素数组以存储最大序列号
无符号长整型x=0;
int Colltz(unsigned long int num,unsigned long int count){//函数启动
无符号长整数j=num;
p[0]=0;//1和2的初始迭代
p[1]=1;//1的初始值
p[2]=2;//3的初始值
while(确定){//while循环
如果((j%2==0)和(&(j/2>num)){/(检查j在数组中是否可用,如果不可用,则进一步将其除以,直到j/2您的代码看起来有点混乱!检查我的解决方案,看看这是否有帮助:
#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);
}
#包括
无符号长整数Collatz(无符号长整数);
int main()
{
无符号长整型n,i,宾果;
int ChainLen=0;
对于(i=1;i ChainLen)
{
ChainLen=n;
宾果=我;
}
}
printf(“\n%lu\n”,宾果);
返回0;
}
无符号长整型衣领(无符号长整型x)
{
如果(x==1)
返回1;
如果(x%2==0)
{
返回1+Collatz(x/2);
}
其他的
返回1+Collatz(x*3+1);
}
查阅此wiki页面,进行适当的修复,您可能会得到更多高质量的响应。欢迎使用Stack Overflow!我很想帮助您,但我不明白您是如何试图解决此问题的。我尝试了标准的暴力方法,在不到一秒钟的时间内就得到了结果。您的代码(对我来说)有点乱您正在初始化函数中的p[0-2],该函数应该在数组声明/定义中,而p的其余部分未知未处理!!!确定的含义和位置让我无法理解。现在最重要的是您设置了p[num],但从未使用它来加速搜索,您应该在函数的开头添加if语句,例如if(p[num]!=0)返回p[num]或者count=p[num]没有决定函数接口的意愿。而且,只有先将p[]数组重置为零值,这才有效!!!如果这无助于添加注释,我会在回答中发布代码