3n + 1 哇伙计们

3n+1 uVa gives WA

我最初的问题有点含糊,所以这是经过编辑的问题。

3n+1 uVa 问题基于 Collat​​z 猜想。 考虑任何正整数 'n'。如果是偶数,则除以2。如果是奇数,则乘以3,再加1。'x'如此反复运算后,就会得到1。这已经被超级计算机证明了非常大的数字。

UVa Online Judge 是巴利亚多利德大学主办的编程问题在线自动评判。

这里有一个 link 问题陈述: uVa 3n+1

看我的代码前请阅读问题陈述! uVa 在线法官针对某些测试用例运行您的代码,并告诉您您的解决方案是对还是错。它不会告诉您它失败的原因(如果您的解决方案是错误的)。

如果您错过了第一个,这里又是 link: The link to the problem description

我不明白我在代码逻辑中遗漏或跳过了什么(因为我得到了错误的答案)。我尝试了很多测试用例,它们似乎工作正常。我知道可以在很大程度上压缩逻辑,但我现在只需要弄清楚缺陷在哪里。

这是我的代码。我知道不应该使用 bits/stdc++,但目前,它不会影响我的代码。如果可以,请审核并帮助我。

#include<iostream>
#include<cstdlib>
#include<bits/stdc++.h>
using namespace std;

int main()
{
unsigned long int num;
int i,j,tempi, tempj,temp;

//Scanning until inputs don't stop
while(scanf("%d %d",&i,&j)!=EOF)
{
//Boolean variable to set if i is greater
bool iwasmore=false;
//Boolean variable for equal numbers
bool equalnums=false;
int cycles=1, maxcycles=0;

if(i>j)
{
//swapping for the for loop to follow
temp=i; i=j; j=temp;
iwasmore=true;
}

if(i==j)
{
    equalnums=true;
}

tempi=i; tempj=j;   

//Taking each number in the given range and running it in the algorithm.
//The maxcycles variable will have the value of the maximum number of cycles
//that one of the numbers in the range took (at the end of the for loop).
for(num=i;num<=j;num=(++tempi))
{
if(cycles>maxcycles)
{
    maxcycles=cycles;
}
cycles=1;
//The actual algorithm
while(num!=1)
    {
        if(num%2==1)
        {
        num = (3*num)+1;
        cycles++;
        }

        else
        {
        num=(num/2);
        cycles++;
        }
    }

    if(equalnums==true)
        {
            maxcycles=cycles;
            equalnums=false;
        }
//Resetting num
    num=0;
}
if(!iwasmore)
cout<<i<<" "<<j<<" "<<maxcycles<<endl;
else
cout<<j<<" "<<i<<" "<<maxcycles<<endl;
}
return 0;
}

这是我为以下输入获得的输出:

输入:

1 1

10 1

210 201

113383 113383

999999 1

输出:

1 1 1

10 1 20

210 201 89

113383 113383 248

999999 1 525

另一个测试用例:

输入:

1 5

10 8

210 202

113383 113383

999999 999989

输出:

1 5 8

10 8 20

210 202 89

113383 113383 248

999999 999989 259

从不将最后检查的数字的周期长度与最大值进行比较。

对于输入:

8 9
9 9

程序输出

8 9 4
9 9 20

但正确答案是

8 9 20
9 9 20

if (cycles > maxcycles) {
    maxcycles = cycles;
}

在 for 循环的结尾,而不是在开头。