12,296,779 members (67,079 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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;
}
```
Posted 14-Nov-12 2:06am
Edited 14-Nov-12 2:51am
v2
Comments
Legor 14-Nov-12 9:28am

Is there any actual question related to this ?
MLOVEternity 15-Nov-12 10:23am

Here is the problem :
http://acm.uva.es/p/v1/100.html[^]
MLOVEternity 15-Nov-12 10:08am

@Jacques Loubser
This is an algorithmic problem in book,Programming challenges.It don't just calculate the answer of (3n + 1).

## 2 solutions

Rate this:
Please Sign up or sign in to vote.

## Solution 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 ;```
Rate this:
Please Sign up or sign in to vote.

## Solution 2

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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Richard MacCutchan 540 Peter Leow 515 OriginalGriff 445 Karthik Bangalore 265 George Jonsson 225
 OriginalGriff 9,250 ppolymorphe 5,476 CHill60 5,260 Karthik Bangalore 4,871 Richard MacCutchan 4,700

Advertise | Privacy | Mobile
Web01 | 2.8.160525.2 | Last Updated 14 Nov 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100