Algoritmo 3n+1 (Maratona de Programação)

Olá, abaixo encontra-se um dos problemas comuns de maratona de programação, dos mais conhecidos, escrito em C++.

#include <iostream>
using namespace std;

/* Pega o tamanho de um ciclo*/
int getOneCicle(int n){
   int oneCicle=0;
   while(oneCicle++,n != 1){
      if(n % 2)
         n = 3*n +1;
      else
         n = n/2;
   }
   return oneCicle;
}

/* Dado dois numeros pega o maior ciclo existente entre estes dois numeros*/
int getGreaterCile(int i , int j){
   int greaterCicle=0,oneCicle=0;

   while(i <= j){
      oneCicle = getOneCicle(i);
      if(oneCicle > greaterCicle)
         greaterCicle = oneCicle;
      i++;
   }

   return greaterCicle;
}

int main(){
   int i,j,greaterCicle;

   while(scanf("%d %d",&i,&j) == 2){

      greaterCicle= i<j ? getGreaterCile(i,j):getGreaterCile(j,i);

      /*saida*/
      printf("%d %d %d\n",i,j,greaterCicle);
   }

   return 0;
}
Compartilhe:
  • Print this article!
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • E-mail this story to a friend!
  • FriendFeed
  • LinkedIn
  • Live
  • MySpace
  • Turn this article into a PDF!
  • Rec6
  • Reddit
  • RSS
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Bookmarks
  • Identi.ca
  • Netvibes
  • Tumblr
  • Twitthis

Nenhum post relacionado.

Tagged : ,

Deixe uma resposta




Spam Protection by WP-SpamFree