【发布时间】:2016-08-29 19:32:29
【问题描述】:
我最初的问题有点含糊,所以这是经过编辑的问题。
3n+1 uVa 问题基于 Collatz 猜想。 考虑任何正整数“n”。如果是偶数,则除以 2。如果是奇数,则将其乘以 3 并加 1。经过 'x' 这样的重复操作,你将得到 1。这已经被超级计算机证明了非常大的数字。
UVa Online Judge 是由巴利亚多利德大学主办的针对编程问题的在线自动裁判。
这是问题陈述的链接: uVa 3n+1
请在查看我的代码之前阅读问题说明! uVa 在线法官针对某些测试用例运行您的代码,并告诉您您的解决方案是对还是错。它不会告诉您失败的原因(如果您的解决方案错误)。
如果您错过了第一个链接,请再次查看链接: 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
【问题讨论】:
-
您缺少或跳过了正确的问题描述。
uVa是什么?WA是什么?你想做什么?什么不起作用? -
你好。我已经给出了问题描述的链接(这里复制粘贴太长了)。Problem Statement
-
如果输入是
1 1,你的程序会输出什么? -
@SaunvedMutalik SO 不需要链接或复制粘贴,而是需要您的描述。
-
顺便说一句,
#include<bits/stdc++.h>不好。