大约3n + 1个问题 [英] About 3n + 1 problem
本文介绍了大约3n + 1个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在编程挑战法官"中提交了答案(在此处 http://www.programming- Challenge.com [ ^ ]).我认为我的代码我是正确的,但它显示的结果是答案错误".
这是代码:
I submit my answer in Programming Challenges Judge(here http://www.programming-challenges.com[^]).I think my code of my is correct,but it show the result that is Answer Wrong.
Here is the code:
// 3n+1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
//declare function for calculate number of sequence of numbers
unsigned int NumOfSquence(unsigned int n);
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int i = 1,j = 1,temp = 0;
cin>>i>>j;
//switch i and j,if(i > j)
if(i > j){
temp = i;
i = j;
j = temp;
}
unsigned int max = NumOfSquence(i);
for(unsigned int k = i + 1;k <= j; k++){
temp = NumOfSquence(k);
if(temp > max){
max = temp;
}
}
cout<<i<<" "<<j<<" "<<max<<endl;
return 0;
}
//the function of calculate number of sequence of numbers,whilch begins with n
// 16 8 4 2 1
unsigned int NumOfSquence(unsigned int n){
unsigned int num = 1;
while(n != 1){
if(n % 2 == 0){
n /=2;
}
else if(n % 2 == 1){
n = 3 * n + 1;
}
num++;
}
return num;
}
推荐答案
嗨
为什么必须这么复杂?
3n + 1 =(3 * n)+1
Hi
Why must it be so complicated?
3n + 1 = (3 * n)+1
unsigned int n = 0;
unsigned int output = 0;
output=( 3 * n ) + 1 ;
从您的代码看来,您正在尝试找到 Collatz猜想的最长的步骤序列 [<在两个初始数字之间的href ="http://en.wikipedia.org/wiki/Collatz_conjecture" target ="_ blank" title ="New Window"> ^ ].
在函数"NumOfSquence"中,您应该从num = 0而不是num = 1开始,以计算步数而不是数字值.
希望对您有所帮助.
It seems from your code that you''re trying find the longest sequence of steps for a Collatz conjecture[^] between 2 initial numbers.
In the function ''NumOfSquence'' you should start from num = 0 instead of num = 1 to count the number of steps instead of the number values.
I hope this helps.
这篇关于大约3n + 1个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文