#UVa:100-The 3n + 1 problem

照著題目所說的去遞迴即可得解。

C++(0.832)

/*******************************************************/
/* UVa 100 The 3n+1 problem                            */
/* Author: LanyiKnight [at] knightzone.org             */
/* Version: 2011/11/23                                 */
/*******************************************************/
#include<iostream>
#include<cstdio>
using namespace std;

int cyclelength( int n );

int main(){
  int i, j, min_i_j, max_i_j;
  int max_length, term_length;
  while( scanf( "%d%d", &i, &j ) != EOF ){
    max_length = 0;
    min_i_j = (i < j)? i : j;
    max_i_j = (i > j)? i : j;
    for( ; min_i_j <= max_i_j ; min_i_j++ ){
      term_length = cyclelength(min_i_j);
      max_length = (term_length > max_length)? term_length : max_length;
    }
    printf( "%d %d %d\n", i, j, max_length );
  }
  return 0;
}

int cyclelength( int n ){
  if( n == 1 )
    return 1;
  else if( n % 2 )
    return 1+cyclelength(3*n+1);
  else
    return 1+cyclelength(n/2);
}

沒有迴響

本文還沒有迴響,快來搶頭香!

發表迴響