#UVa:694-The Collatz Sequence

灆洢 2012-11-28 23:54:43

照著題目要求去進行遞迴,即可得解。

C++(0.024)

/*******************************************************/
/* UVa 694 The Collatz Sequence                        */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2012/11/28                                 */
/*******************************************************/
#include <iostream>
#include <cstdio>
using namespace std;

int f( long long A, long long L ){
  if( A == 1 ) return 1;
  else if( A % 2 == 0 ) return 1+f(A/2,L);
  else{
    if( 3*A+1 > L ) return 1;
    return 1+f(3*A+1,L);
  }
}

int main(){
  long long A, L;
  int testcase = 1;
  while( scanf( "%lld%lld", &A, &L ) != EOF && !(A < 0 && L < 0)){
    printf( "Case %d: A = %lld, limit = %lld, number of terms = %d\n", testcase++, A, L, f(A,L) );
  }
  return 0;
}

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料