이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

3n+1 Problem

어떤 정수 n에서 시작해, n이 짝수면 2로 나누고, 홀수면 3을 곱한 다음 1을 더한다. 이렇게 해서 새로 만들어진 숫자를 n으로 놓고, n=1 이 될때까지 같은 작업을 계속 반복한다. 예를 들어, n=22이면 다음과 같은 수열이 만들어진다.

22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

n이라는 값이 입력되었을때 1이 나올때까지 만들어진 수의 개수(1을 포함)를 n의 사이클 길이라고 한다. 위에 있는 수열을 예로 들면 22의 사이클 길이는 16이다. i와 j라는 두개의 수가 주어졌을때, i와 j사이의 모든 수(i, j포함)에 대해 최대 사이클 길이를 구하라.

입력 예

1    10
100  200
201  210
900  1000

출력 예

1    10    20
100  200   125
201  210   89
900  1000  174

※ 참고

어떤 자연수 n에 대해서도, 이 조작을 유한 번 시행하면 1이 될 것이라고 예상하는데, 700,000,000,000보다 작은 모든 짝수에 대해 성립한다는 것이 밝혀져 있긴 하지만, 아직 아무도 증명하지 못했습니다. 유명한 헝가리 수학자 폴 에르되시(Paul Erd' os)는, "우리의 수학은 아직 이 문제를 풀 준비가 되어 있지 않다." 라고 했습니다.

2014/02/28 16:42

pahkey

368개의 풀이가 있습니다.

python 입니다.

def cypro(k):
    cl=1
    while k != 1:
        if k%2==0:
            k=k/2
            cl+=1
        else:
            k=3*k+1
            cl+=1
    return cl

i=int(input('INPUT MIN NUM : '))
j=int(input('INPUT MAX NUM : '))
t=0
arw=[]

for t in range(i,j+1):
    arw.append(cypro(t))
print(max(arw))

2014/04/26 22:10

장 진욱

가독성이 좋네요. 감사합니다. - Kookeedd, 2019/03/22 12:45

Java입니당

package h25_3nplus1; import java.util.Scanner;
public class Threenplus1 {
    public static void main(String[] args) {
        Scanner num=new Scanner(System.in);
        int a=num.nextInt(), b=num.nextInt(), i, n=0, max=0; //a,b입력
        for(;a<=b;a++){ //입력한 a부터 b까지 연산하기위해
            for(n=1, i=a; i>1; n++){ //하나의 수를 1이 나올때까지 연산, n구하기
                if(i%2==0) i/=2; else i=i*3+1; //연산
            } if(max<n) max=n; //연산 중 최대의 n구하기
        } System.out.println(max); //출력
    }
}

2014/03/08 20:25

Katherine

파이썬 2.7에서 작성하였습니다.

def cycle(n):
    count = 1
    while n != 1:
        count += 1
        n = -(n%2-1)*(n/2) + (n%2)*(n*3+1)
    return count

def test(n1,n2):
    dist = [cycle(x) for x in range(n1,n2+1)]
    dist.sort()
    return dist[-1]

2015/01/20 12:23

SPJung

Ruby

def get_max_cycle(lower, upper)
  f = lambda do |x| 
    return x if x[-1] == 1
    x[-1] % 2 == 0 ? f[[*x, x[-1] / 2]] : f[[*x, x[-1] * 3 + 1]]  
  end  

  "#{lower}\t#{upper}\t#{lower.upto(upper).map{|i| f[[i]].length}.max}"
end

테스트

require 'test/unit'
extend Test::Unit::Assertions

assert_equal get_max_cycle(1, 10), "1\t10\t20"
assert_equal get_max_cycle(100, 200), "100\t200\t125"
assert_equal get_max_cycle(201, 210), "201\t210\t89"
assert_equal get_max_cycle(900, 1000), "900\t1000\t174"

2014/03/01 04:56

nacyot

Scala로 풀었습니다.

def cycleLength(n:Int, cnt:Int=1):Int = {
  if(n == 1) cnt
  else if(n % 2 == 0) cycleLength(n / 2, cnt + 1)
  else cycleLength(n * 3 + 1, cnt + 1)
}
def f(i:Int, j:Int) = (i to j).map(cycleLength(_)).max

2015/01/21 00:02

이 호연

UINT를 ULL로 바꿔야 맞는데...하하

#include <iostream>
#include <map>
#include <cstdio>
#include <cstring>

#define MAX_NUM 1000000
typedef unsigned long long UINT;

UINT getCycle(UINT number, UINT* table);

int main()
{
   UINT* table = new UINT[MAX_NUM+1];
   UINT st;
   UINT end;
   memset(table, 0, (MAX_NUM+1)*sizeof(UINT));

   while (scanf("%llu %llu",&st,&end)==2)
  { 

     UINT max_cycle = 0;

     UINT val1;
     UINT val2;     
     if(st > end)
     {
         val1 = end;
         val2 = st;
     }else{
         val1 = st;
         val2 = end;
     }

     for(UINT i = val2; i >= val1; i--)
     {
         UINT cycle = getCycle(i, table);

         if(table[i] == 0)
            table[i] = cycle;

         if(max_cycle < cycle)
             max_cycle = cycle;
     }

     std::cout<<st<<" "<<end<<" "<<max_cycle<<std::endl;

  }
   delete [] table;
   return 0;
}


UINT getCycle(UINT number, UINT* table)
{
   UINT cnt = 1;
   while(number != 1)
   {
      if(number <= MAX_NUM)
      {
         if(table[number] != 0)
         {
            cnt += (table[number] - 1);
            break;
         }
      }

      if(number % 2 == 0)
         number = number / 2;         
      else 
         number = 3*number +1;

      cnt++;
   }
   return cnt;

}

2015/07/11 08:26

Dong-hee, Na

Python3에서 작성하였습니다. 재귀함수와 Memoization 기법을 사용하였습니다.

cache = { 1: 1 }
def cycle(n):
    if n in cache: return cache[n]
    cache[n] = 1 + (cycle(n * 3 + 1) if n % 2 else cycle(n // 2))
    return cache[n]

i = 900
j = 1000
mcl = 0 # max cycle length
for n in range(i, j + 1):
    mcl = max(mcl, cycle(n))
print(mcl)

2022/05/15 16:32

Euijin

(defn problem-3n+1
  ([n]
   (problem-3n+1 n 1))
  ([n cycle]
   (if (= n 1)
     cycle
     (recur (if (even? n)
              (/ n 2)
              (+ (* 3 n) 1))
            (inc cycle)))))

(defn between-i-j [i j]
  (println (format "%-5d %-5d %-5d"
                   i
                   j
                   (reduce max (map problem-3n+1 (range i (inc j)))))))

Clojure 코드입니다.

2014/02/28 17:37

박연오

def sol(n):
    print(n, end=" ")
    if (n==1):
        return 0
    elif not n%2:
        sol(n//2)
    else:
        sol(3*n+1)

>> sol(22)

>> 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

2014/02/28 19:04

정훈

파이썬입니다.^^ 좀더 깔끔하게 될거 같은데 뭔가 아쉽네요

beginNumber =int(input("input begin number: "))
lastNumber  =int(input("input last number: "))

def getCycle(n):
    _list = [n]
    while True:
        if n % 2 == 0:
            n = n / 2
            _list.append(int(n))
        else:
            n = n * 3 + 1
            _list.append(int(n))
        if n == 1:
            break
    return len(_list)

def getProblemMax(n,x):
    totalSum = []
    for y in range(beginNumber,lastNumber+1):
        totalSum.append(getCycle(y))

    return max(totalSum) 

print(getProblemMax(beginNumber,lastNumber))

2014/03/11 14:18

무명소졸

Memoizatio을 사용하여 메모리를 조금 더 쓰는 대신에 속도는 더 빠를 겁니다.

def threeone(n)
    @hsh ||= {}
    return 1 if n <= 1
    return @hsh[n] if @hsh.include?(n)          

    if n % 2 == 0
        next_n = n/2 
    else
        next_n = 3*n+1
    end
    @hsh[n] = threeone(next_n) + 1
end



STDIN.read.split(/[\r\n]/).each do |data|
    first, last = data.split.map{|e| e.to_i }

    ans = (first..last).max_by{|e| threeone(e) }
    puts "#{first} #{last} #{threeone ans}"
end

2014/03/11 16:20

Kim Jaeju

파이썬으로 작성해보았습니다. 초보라서 티가 팍팍나네요..ㅠㅠ

def n3n1(i,j):
    mxcl = 0
    for i in range(i,j+1,1):
        cl = 1
        while i != 1:
            if i%2 == 0:i = i/2
            else : i = i*3 + 1
            cl+=1
        if mxcl < cl: mxcl = cl
    return mxcl

2014/03/16 01:56

umtie

clojure

(defn do-3n1 [n]
  (if (even? n)
    (/ n 2)
    (+ (* 3 n) 1)))



(defn get-3n1-cnt [n]
  (->> n
       (iterate do-3n1)
       (take-while #(not= % 1))
       count
       inc))


(for [[from to] [[100  200]
                 [201  210]
                 [900  1000]]]
  (->> (range from (inc to))
       (map get-3n1-cnt)
       (apply max)))

2014/03/23 07:04

김 은평

파이썬 객체로 풀어보았습니다. 태클 환영요~ by phantom

class answer:
    class template:
        count = 1;
        def __init__(self,num):
            self.mynum = num
        def func(self):
            if self.mynum%2 ==1:
                self.mynum = 3*self.mynum +1
            else:
                self.mynum = self.mynum/2
        def func1(self):
            while self.mynum <> 1:
                self.func()
                self.count += 1
            return self.count

    def show(self,i,j):
        li = []

        for x in range(i,j):
            y = self.template(x)
            li.append(y.func1())
            del y

        print max(li)   

2014/03/29 03:52

phantom

재귀호출연습겸!

    public static int getMaxCycle(int start, int end){
        int maxCount = 0;
        for(int i = start ; i<=end; i++){
            int count = 0;
            count+=getCountCycle(i);
            if(count>maxCount)
                maxCount=count;
        }
        return maxCount;
    }

    public static int getCountCycle(int n){
        int ret=0;
        if(n==1)return ret+1;
        if(n%2==0){
            ret++;
            ret+=getCountCycle(n/2);
        }else{
            ret++;
            ret+=getCountCycle(n*3+1);
        }

        return ret;

    }

2014/03/29 05:00

김 종택

#include <stdio.h>

int get_cycle(int n) {
    int count = 1;
    while (n != 1) {
        if (n % 2 == 0) { // even
            n = n / 2;
        } else {
            n = n * 3 + 1;
        }
        count++;
    }
    return count;
}

int main() {
    int start, end;
    int n;

    printf("Enter number:");
    scanf("%d %d", &start, &end);

    int max = -1;
    int temp;
    for (n = start; n <= end; n++) {
        temp = get_cycle(n);
        if (temp > max) {
            max = temp;
        }
    }
    printf("%-5d %-5d %-5d", start, end, max);
    return 0;
}

2014/04/07 17:26

pahkey

문제만 보고 풀었는데, 제가 짠 코드와 99% 일치하네요 !! 신기함 ㅋ - 무아딥, 2015/08/19 11:21

Python

def problem(n):
    result = [n]
    while n > 1:
        if n % 2 == 0:
            n /= 2
            result.append(n)
            problem(n)
        else:
            n = 3 * n + 1
            result.append(n)
            problem(n)
    return result

def cycle_len(i,j):
    result = []
    for x in range(i, j + 1):
        result.append(len(problem(x))
    return max(result)

i = input('i:')
j = input('j:')
print cycle_len(i, j)             

아직 초보라 1차원적으로 생각해서 풀어 봤는데 숫자가 조금 커지면 시간이 너무 오래 걸리네요

2014/04/16 17:53

호옹이

class Cicle:
    a=0
    b=0
    cicleLength=[]
    def __init__(self, a, b):
       self.a=a
       self.b=b
    def cicle(self):
        for n in range(int(self.a),int(self.b)+1):
            countCicle=0
            while(1):
                if n==1:
                    countCicle+=1
                    break
                elif n%2==0:
                    n=n/2
                    countCicle+=1
                elif n%2==1:
                    n=(n*3)+1
                    countCicle+=1
            self.cicleLength.append(countCicle)

def main():
    a=input()
    b=input()
    cicle=Cicle(a, b)
    cicle.cicle()
    print(cicle.cicleLength,"max :",max(cicle.cicleLength))

main()

2014/05/05 20:04

고 윤호

파이썬입니다.

list_cycle =[]
i = int(input(" Input First number : "))
j = int(input(" Input Last  number : "))

def calc(n):
        cycle = 1
        while  n != 1:
                if n % 2 == 0:n = n / 2
                else:n = n * 3 + 1
                cycle = cycle + 1
        list_cycle.append(cycle)

for number in range(i, j+1):
        calc(number)

print(" Max Cycle  length  : %d" % max(list_cycle))

결과입니다.

 Input First number : 100
 Input Last  number : 200
 Max Cycle  length  : 125

2014/05/07 15:02

재민스

Python

def cycle(n):
    total_number = 0
    while n != 1:
        if n % 2 == 0:
            n = n/2
            total_number += 1
        else:
            n = n * 3 + 1
            total_number += 1
    return total_number

Max = int(input('최대 값을 적으시오: '))
Min = int(input('최소 값을 적으시오: '))
total = []

for number in range(Min,Max + 1):
    total += [cycle(number)]

sequence_number = sorted(total)

print(Min,'과',Max,'사이에서 최대 큰 싸이클 수는: ',sequence_number[-1] + 1)

2014/05/19 23:52

Heong Jun Yoo

import sys

def ncycle(num):
        val = int(num)
        cycle = 1
        while val != 1:
                if val % 2 == 0:
                        val /= 2
                else:
                        val = val*3 + 1
                cycle += 1
        return cycle

def maxcycle(a, b):
        result = []
        a = int(a)
        b = int(b)
        for i in range(a, b):
                result.append(ncycle(i))
        return max(result)

print sys.argv[1], sys.argv[2], maxcycle(sys.argv[1], sys.argv[2])

2014/05/26 17:46

superarchi

python 3.4

def brain(n):
    if n % 2 == 0: return n / 2
    else: return n * 3 + 1

def loop(n):
    count = 1
    while 1:
        if n == 1: break

        n = brain(n)
        count += 1
    return count

def maker(x,y):
    diff = loop(x)
    for i in range(x,y+1):
        if diff < loop(i):
            diff = loop(i)

    return diff

print(maker(1,10))
print(maker(100,200))
print(maker(201,210))
print(maker(900,1000))

2014/06/04 10:26

Oh Sungmin

python 2.7.3 굳이 설명이 필요없을듯 하네요.

problemS = raw_input()
tempL = problemS.split(' ')
problemL = [int(i) for i in tempL]
maxCycle = 0

for i in range(problemL[0], problemL[1]+1) :
    num = i
    cycle = 1

    while num > 1 :
        if num%2==0 : #even
            num /= 2
        else :
            num = num*3 + 1
        cycle += 1

    if maxCycle < cycle :
        maxCycle = cycle

print problemL[0], problemL[1], maxCycle

2014/06/09 13:53

suker


public class c_3n1problem {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] i = {1,100,201,900};
        int[] j = {10,200,210,1000};
        for(int n = 0 ; n < i.length ; n ++){
            int maxLen = new c_3n1problem().getNumHasMAXCycleLenght(i[n], j[n]);
            System.out.println(i[n] + "  " + j[n] + "  " + maxLen);
        }
    }

    private int getNumHasMAXCycleLenght(int i, int j){
        int max = 0;
        for(int n = i ; n <= j ; n ++){
            int len = getCycleLength(n);
            if (len > max)
                max = len;
        }

        return max;
    }
    private int getCycleLength(int n){
        int length = 0 ;
        while(n != 1){
            if(n%2 == 0){
                n = (int)n/2;
            }
            else {
                n = n * 3 + 1;
            }
//          System.out.print(n + " ");
            length++;
        }
//      System.out.println();
//      System.out.println("length = " + (length+1));
        return length+1;
    }
}

2014/06/19 20:11

ministar

python 3.4입니다.

import unittest
def get_cycle(n):
    cycle = [n]
    while(not n == 1):
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
        cycle.append(n)
    return cycle

def get_cycles(n1, n2):
    cycles = []
    for i in range(n1, n2+1):
        cycles.append(get_cycle(i))

    return cycles

def method1(n1, n2):
    cycles = get_cycles(n1, n2)
    max_len_cycles = len(cycles[0])

    for cycle in cycles:
        if len(cycle) > max_len_cycles:
            max_len_cycles = len(cycle)

    return max_len_cycles

def method2(n1, n2):
    cycles = get_cycles(n1, n2)
    len_cycles = [len(n) for n in cycles]

    return max(len_cycles)

class TestThreeN(unittest.TestCase):
    def test_solution(self):
        self.assertEqual(method1(22,22), 16)
        self.assertEqual(method1(1, 10), 20)
        self.assertEqual(method1(100, 200), 125)
        self.assertEqual(method1(201, 210), 89)
        self.assertEqual(method1(900, 1000), 174)

        self.assertEqual(method2(22,22), 16)
        self.assertEqual(method2(1, 10), 20)
        self.assertEqual(method2(100, 200), 125)
        self.assertEqual(method2(201, 210), 89)
        self.assertEqual(method2(900, 1000), 174)

    def test_get_cycle(self):
        self.assertEqual(get_cycle(22), [22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1])

    def test_get_cycles(self):
        self.assertEqual(get_cycles(22, 22), [[22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]])


if __name__ == "__main__":
    unittest.main()



2014/07/23 09:42

이 정구

def cal_cycle(num):
    count = 0
    while num != 1:
        if num % 2 == 0:
            num = num / 2
        else:
            num = 3 * num + 1
        count += 1
    count += 1
    return count

num_i = int(raw_input("Enter i : "))
num_j = int(raw_input("Enter j : "))

max_cycle = max([cal_cycle(x) for x in range(num_i, num_j+1)])

print str(num_i) + "  " + str(num_j) + "  " + str(max_cycle)

2014/07/23 18:20

하태욱

JAVA

package AlorithmPractice;

public class problem3n {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] input= {{1,10},{100,200},{201,210},{900,1000}};

        calculator.getExecuteCalculator(input);
    }
    private static class calculator{
        private int[][] input;
        private int[] result;
        private calculator(int[][] input){
            this.input=input;
            this.result= new int[input.length];
            work();
        }
        public static calculator getExecuteCalculator(int[][] input){
            return new calculator(input);
        }
        public void work(){
            loop();
            print();
        }
        public void print(){
            for(int i=0;i<input.length;i++){
                System.out.println(input[i][0]+"\t"+input[i][1]+"\t"+result[i]);
            }
        }       
        private void loop(){
            //System.out.println("Ok");
            for(int i=0;i<input.length ;i++){
                int[] innerArr=input[i];
                int start=innerArr[0];
                int end=innerArr[1];
                int maxCycle =0;
                for(int index=start;index<end;index++){
                    int currentCycle =getCycleRoad(index);
                    if(currentCycle>maxCycle)maxCycle=currentCycle;
                }
                //System.out.println(result[i]);
                result[i]=maxCycle;             
            }           
        }
        private int getCycleRoad(int input){
            int result = 1;
            int process=input;
            while(process!=1){
                if(process%2==0){
                    process /= 2;
                }
                else{
                    process = (3*process) +1;
                }
                result++;
            }           
            return result;
        }

    }

}
**Output**
1   10  20
100 200 125
201 210 89
900 1000    174

원래기능은 그닥 없는데... 괜히 OOL 흉내내본답시고 해서 코드만 길어졌네요 ㅋㅋ;;

2014/07/24 16:10

노동현

// 언어 : Swift
import Foundation

func NumToOne(var n:Int,var m:Int) -> Void
{
    if n > m {
        let tmp = n;
        n = m;
        m = tmp;
    } // 1번 인자가 더 크다면 두개의 값을 바꿔줌

    let Calculation: Int -> Int = {
        (num: Int) in
        if (num%2) != 0 { return num*3+1; }
        return num/2;
    }; // 짝수면 2 나누고 홀수면 3곱한후 1더해서 반환

    var count = 0; // 1까지 얼마나 거리는지
    var result = 0; // 가장큰 반복횟수

    for i in n...m // n ~ m 까지
    {
        var tmp = i;
        while tmp > 1 // 1이 될때까지 반복
        {
            tmp = Calculation(tmp);
            count++; // 한번계산후 카운트 증가
        }

        if result < count { result = count+1; }
        count=0; // 반복횟수가 더 많았다면 기록
    }
    println(result);
} // End of Function

NumToOne(1,20)

2014/09/02 02:39

식빵

#include <iostream>
using namespace std;

static int cycle = 0;

void computeCycle(int n) {
    cycle++;

    if (n == 1)
        return;

    if (n%2 == 0 )
        n /=2;
    else
        n = 3*n +1;
    return computeCycle(n);
}

int main ()
{
    int input1  = 1, input2  = 10;

    int maxCycle = -1;

    for (int i=input1; i<= input2; i++) {
        computeCycle(i);
        if ( cycle > maxCycle) {
            maxCycle = cycle;
        }
        cycle = 0;
    }

    cout << input1 << "\t" << input2 << "\t" << maxCycle << endl;

    return 0;
}

2014/09/10 23:16

Jason

루비입니다.


def max_cycle(number)
  nums = Array.new
  val = 0
  while number != 1
    if number%2 ==0
      val = number/2
    else
      val = number*3+1
    end
    number = val
    nums.push(val)
  end
  nums_count = nums.count+1
end

def between_max_cycle(start_number, last_number)
  nums = Array.new
  action_number = start_number
  stop_number = last_number+1
  while action_number != stop_number
    nums.push(max_cycle(action_number))
    action_number += 1
  end
  puts nums.max
end



리팩토링 이후 테스트 코드 포함


def max_cycle(number)
  return 0 if number == 0
  result = [number]
  while number != 1
    if number%2 ==0
      number = number/2
    else
      number = number*3+1
    end
    result.push(number)
  end
  result.count
end

def between_max_cycle(start_number, last_number)
  (start_number..last_number).map do |number|
    max_cycle(number)
  end.max
end

require 'minitest/autorun'

class TestThreePlusOne < Minitest::Test
  def test_max_cycle
    assert_equal(16, max_cycle(22) )
    assert_equal(7, max_cycle(10) )
    assert_equal(0, max_cycle(0) )
  end

  def test_between_max_cycle
    assert_equal(125, between_max_cycle(100, 200) )
  end
end

2014/09/24 11:28

Cha Semo

자바입니다.

package my_test;
public class T {
    public static void main(String[] args) {
        int num1=100;
        int num2=200;

        System.out.println(cal(num1,num2));
    }

    public static int cal(int num1, int num2){
        int ct=1;
        int max=0;
        for(int i=num1;i<=num2;i++){
            for(int j=i;j!=1;){
                ct++;
                if(j%2==0){
                    j=j/2;
                }else{
                    j=j*3+1;
                }
            }
            System.out.println(i+"의 수:"+ct);
            if(ct>max){max=ct;}
            ct=1;
        }

        return max;
    }

}

2014/09/26 18:12

임시

#include <stdio.h>

int main() {
    int i, j, times = 0, max = 0, num;
    scanf("%d %d", &i, &j);
    for (int n = i; n <= j; n++) {
        num = n;
        times = 1;
        while (1) {
            if (num % 2 == 0)
                num /= 2;
            else
                num = num * 3 + 1;
            times++;
            if (num == 1)
                break;
        }
        if (times > max)
            max = times;
    }
    printf("%d", max);
    return 0;
}

2014/09/27 22:47

좋은게좋은거

C#

using System;

class Program
{
    static int[] start = new int[] { 1, 100, 201, 900 };
    static int[] end = new int[] { 10, 200, 210, 1000 };

    static void Main()
    {
        for (var i = 0; i < start.Length; i++)
        {
            var maxCycle = 0;

            for (var k = start[i]; k <= end[i]; k++)
            {
                var n = k;
                if (n == 1)
                {
                    continue;
                }
                var cycle = 1;
                while (true)
                {
                    if (n == 1)
                    {
                        break;
                    }
                    if (n % 2 == 0)
                    {
                        n /= 2;
                    }
                    else
                    {
                        n = n * 3 + 1;
                    }
                    cycle++;
                }

                if (maxCycle < cycle)
                {
                    maxCycle = cycle;
                }
            }

            Console.WriteLine("{0}  {1} {2}", start[i], end[i], maxCycle);
        }
    }
}

2014/09/29 14:35

보헤미안

파이썬 3.4 입니다.

def my_series(number):
    series = [number]
    while number != 1:
        if number %2 == 0:
            number = number / 2
        else:
            number = number * 3 + 1
        series.append(number)
    result = len(series)
    return result

input_list = (input().strip()).split(" ")
i = int(input_list[0]); j = int(input_list[1])
input_list = list(range(i,j+1))
cycle_list = list(map(my_series, input_list))
print (max(cycle_list))

class 를 이용해서 고쳐보았습니다. 딱히 필요한 줄 모르겠지만 최근에 공부한 개념을 연습하는 차원에서 ^^;;

class MySeries:
    def __init__(self,i,j):
        self.i = i; self.j = j
        self.input_list = list(range(self.i,self.j+1))
        self.cycle_list = []

    def __get_series(self,number):
        series = [number]
        while number != 1:
            if number %2 == 0: number = number / 2
            else: number = number * 3 + 1
            series.append(number)
        result = len(series)
        return result

    def max_cycle(self):  
        for number in self.input_list:
            result = self.__get_series(number)
            self.cycle_list.append(result)
        return max(self.cycle_list) 

input_list = (input().strip()).split(" ")
i = int(input_list[0]); j = int(input_list[1])
ms = MySeries (i,j)
print(ms.max_cycle())

2014/10/05 14:36

돌구늬ㅋ~썬

    private static int getMaxCycle(int a, int b) {
        int maxCycle = 1;
        int cnt = 1;
        int value = 0;

        while (a <= b) {
            if (cnt == 1) {
                value = a;
            }
            if (value % 2 == 0) {
                value = value / 2;
            } else {
                value = (value * 3) + 1;
            }
            cnt++;
            if (value == 1) {
                if (maxCycle < cnt) {
                    maxCycle = cnt;
                }
                a++;
                cnt = 1;
            }
        }

        return maxCycle;
    }

2014/11/10 12:09

아그네스

Ruby, Recursion

def series(n)
  s = [n]
  return s if n == 1
  return s += series(n / 2) if n.even?
  return s += series(n * 3 + 1)
end

def max_cycle(from, to)
  cycles = (from..to).map { |v| (series v).length }
  puts "#{from} #{to} #{cycles.max}"
end

2014/12/30 17:28

놀란눈

python 입니다.

import unittest

def func(s, cycle=0):
  l = s.split(" ")
  for n in range(int(l[0]), int(l[1])+1):
    newcycle = 1 
    while n != 1 : 
      if n%2==0 : n = n/2 
      else : n = 3*n+1 
      newcycle += 1 
    if cycle < newcycle : cycle = newcycle 
  return l[0] + ' ' + l[1] + ' ' + str(cycle) 

class Test(unittest.TestCase):
  def test1(self):
    self.assertEqual('1 10 20', func('1 10'))
    self.assertEqual('100 200 125', func('100 200'))
    self.assertEqual('201 210 89', func('201 210'))
    self.assertEqual('900 1000 174', func('900 1000'))

if __name__ == "__main__":
  unittest.main()

2015/01/12 11:49

Sang Brian

펄입니다

use latest;
my($from,$to)=@ARGV;
sub cycle_length
{
    my $n=$_[0];
    my $c=1;

    do
    {
        unless($n%2){$n/=2}
        else{$n=3*$n+1}
        $c++;
    }until($n==1);
    $c;
}
my $max=0;
my $t;
for($from..$to)
{
    if(($t=cycle_length($_))>$max){$max=$t}
}
say $max;

2015/01/24 08:54

이병곤

루비입니다. 조금 큰수로 해야하면 memoize해야할 테지만 지금 예제는 이걸로도 별 문제 없더라구요.

def n_length(number)
  if number == 1
    1
  elsif number.even?
    1 + n_length(number / 2)
  else
    1 + n_length(3 * number + 1)
  end
end

p     (1..10).map { |n| n_length(n) }.max
p  (100..200).map { |n| n_length(n) }.max
p  (201..210).map { |n| n_length(n) }.max
p (900..1000).map { |n| n_length(n) }.max

2015/01/31 15:10

Shim Won

Using python

#!/usr/bin/python
# -*- coding:utf-8 -*-

def nPlus1(m,n):
    b = 0
    for num in range(m,n+1):
        a = 1
        while num != 1:
            if num%2 == 0:
                num = num/2
                a += 1
            else:
                num = num*3+1
                a += 1
        if b < a:
            b = a
    return b

def main():
    rng1,rng2 = raw_input("Define range : ").split()
    print nPlus1(int(rng1),int(rng2))

if __name__=="__main__":
    main()

2015/04/02 16:23

freeefly

import java.util.*;
public class main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System. in);
        System.out.println("숫자를 입력하세요");
        int a = sc.nextInt();

        while(a>=1){
            if(a==1)
                break;
            if(a%2 == 0){
                a = a/2;
                System.out.print(a+" " );
            }
            else{
                a = a*3+1;
                System.out.print(a+" " );
            }
        }

        }
    }

2015/05/01 11:40

김 성환

python 2.7이에요 ㅎㅎ 파일 입출력으로 풀어봤습니다.

#409.py
def chain(i,count=0):
    # calculate length of chain
    count+=1
    if i==1:
        return count
    elif i%2==0:
        return chain(i/2,count)
    else:
        return chain(i*3+1,count)

def max_length(i,j):
    #calculate the answer of the question.
    result=0
    for t in range(i,j+1):
        result=max(chain(t),result)
    return result

# file read/write
f=open("input.txt","r")
g=open("output.txt","w")
line=f.readlines()
for x in line:  
    ab=x.split(" ")
    ab[1]=str(int(ab[1]))
    ab.append(str(max_length(int(ab[0]),int(ab[1])))+"\n")
    print ab
    g.write(" ".join(ab))
g.close()

2015/05/04 11:47

심재용

#include <stdio.h>
void spy(int a, int b)
{
    int d[10001],i, e, c, j= -1;
    for(i=a;i<=b;i++)
    {
        c=1;
        e=i;
        for(;;)
        {
            if(e==1)break;
            c++;
            if(e%2==1)e=e*3+1;
            else e=e/2;
        }
        d[i]=c;
    }
    for(i=a;i<=b;i++)
    {
        if(d[i]>j) j=d[i];
    }
    for(i=a;i<=b;i++)
    {
        if(j==d[i])break;
    }
    printf("%d",j);
}
int main()
{
   int a,b;
   scanf("%d %d",&a,&b);
   spy(a,b);
}

2015/06/12 23:54

코딩호빵이

    Sub main()
        Dim n() As Integer = Array.ConvertAll(Split(Console.ReadLine, " "), Function(s As String) CInt(s))

        Dim getCycle As Func(Of Integer, Integer) =
            Function(num As Integer) As Integer
                Dim cnt As Integer = 1

                While num <> 1
                    cnt += 1

                    If num Mod 2 = 0 Then
                        num /= 2
                    Else
                        num = num * 3 + 1
                    End If
                End While

                Return cnt
            End Function

        Dim r() As Integer = Enumerable.Range(n(0), n(1) - n(0)).Select(
            Function(num As Integer) getCycle(num)).ToArray

        Console.WriteLine("Result: " & r.Max)

        Console.ReadLine()
    End Sub

2015/06/13 02:28

Steal

맞았는지 모르겠어요...

a,b = map(int,input("number?").split())
count = 0
count_list = []
for i in range(a+1,b):
    oneCycle = False
    while not oneCycle:
        if i%2 == 0:
            i = i/2
            count += 1
        elif i != 1:
            i = 3*i+1
            count += 1
        else:
            oneCycle = True
            count += 1
            count_list.append(count)
print(max(count_list)

2015/07/14 15:48

renee

static int getPaulC(int n)
    {
        int cnt = 1;

        while (n > 1)
        {
            if (n % 2 == 0)
                n /= 2;
            else
                n = (n * 3) + 1;

            cnt++;
        }

        return cnt;
    }

    static void exce23()
    {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt(), b = scan.nextInt();
        int n = -1;

        for (int i = a; i <= b; i++)
        {
            if (getPaulC(i) > n)
            {
                n = getPaulC(i);
                System.out.printf("!!%d %d\n", i, getPaulC(i));
            }
        }

        System.out.println(n);

    }

2015/08/21 10:12

조서현

def three_one_algorithm(stnum, ednum):
    countmax = 0

    for i in range(stnum, ednum + 1):
        count = 1
        while i != 1:
            if i % 2 == 0:
                i = i / 2
            else:
                i = 3 * i + 1
            count = count + 1
        countmax = max(count, countmax)    
    return countmax

2015/09/08 00:21

박 해수

        static void Main(string[] args)
        {
            string[] read = Console.ReadLine().Split(' ');
            int min = int.Parse(read[0]);
            int max = int.Parse(read[1]);
            int result = 0;
            for(int i = min;i<=max;i++)
            {
                int c = Circle(i);
                if(result < c)
                {
                    result = c;
                }
            }
            Console.WriteLine(result);
        }
        static int Circle(int n)
        {
            int count = 1;
            while(n != 1)
            {
                n = n % 2 == 0 ? n / 2 : (n * 3) - 1;
                count++;
            }
            return count;
        }

2015/09/26 23:31

정우진

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    int i, j, max, n,index,count_cycle;
    max=1; 

    scanf("%d %d",&i,&j); //i와 j의 값 입력 받음 

    for(index=i; index<=j; index++){
        n=index; 
        for(count_cycle=1; n!=1; count_cycle++){
            if(n%2==0) n=n/2; 
            else n=(3*n)+1; 
        }
        if(max<count_cycle) max=count_cycle; 
    }
    printf("%d %d %d",i,j,max); 

    return 0;
}

C언어

2015/10/09 18:57

Kicia Park

Swift로 작성하였습니다. Dictionary에 길이를 넣어 cache 기능을 사용하도록 하였습니다.

func main(x x: Int, y: Int) -> (Int, Int) {
    func hailstoneSequence(var cacheSequence: [Int:Int]) -> Int -> Int {
        func hailstoneSequenceF(n: Int) -> Int {
            if n == 1 { return 1 }
            if let cached = cacheSequence[n] { return cached }
            let result = 1 + ( (n % 2 == 0) ? hailstoneSequenceF(n/2) : hailstoneSequenceF(n*3+1))
            cacheSequence[n] = result
            return result
        }
        return hailstoneSequenceF
    }

    return (x...y).reduce( (result: (0, maximum: 0), f: hailstoneSequence([Int:Int]())) ) {
        let length = $0.0.f($0.1)
        if length > $0.0.result.maximum {
            return (($0.1, length), $0.0.f)
        }
        return $0.0
    }.result
}

[(1, 10), (100, 200), (201, 210), (900, 1000)].forEach {
    let result = main(x: $0.0, y: $0.1)
    print(String(format: "%4d", $0.0), String(format: "%4d", $0.1), String(format: "%4d", main(x: $0.0, y: $0.1).1))
}
/* Output
1   10   20
100  200  125
201  210   89
900 1000  174
*/

2015/10/12 01:20

Ahn Jung Min

python3입니다.

def cycleLen(n):
    if n == 1: return 1
    if n % 2 == 0: return 1 + cycleLen(n / 2)
    return 1 + cycleLen(n * 3 + 1)

def sol(i, j):
    return max([cycleLen(x) for x in range(i, j + 1)])

print(sol(1, 10))

2015/11/26 14:36

jspark

n = int(input('enter : '))
l=[]
l.append(n)
while(n!=1):
     if n%2==0:
          n=int(n/2)
     elif n%2==1:
          n=int(3*n+1)
     l.append(n)


2015/12/24 13:28

창자.

  • python으로 작성하였습니다.
i,j=map(int,raw_input('type i~j :').split('~'))

def cntCycle(s):
    cnt=1 
    while(s>1):
        if s%2==0:
            s/=2
        else:
            s=s*3+1
        cnt+=1
    return cnt

res=[]
for i in range(i,j+1):
    res.append(cntCycle(i))
print max(res)

2016/01/08 09:07

씨니컬우기님

'''
한번 계산했던 결과값은 사전에 저장해서
이용하도록 해보았습니다.
'''
cycle_dic = {}
def cycle(n):
    counter = 0
    while True:
        if cycle_dic.has_key(n): return counter+cycle_dic[n]
        if n&1 == 0 : n /= 2
        else : n=3*n+1
        counter += 1
        if n == 1:
            cycle_dic[n] = counter+1
            return counter+1
while True:
    i,j = map(eval, raw_input().split())
    print max(cycle(n) for n in range(i,j+1))

2016/01/17 22:29

상파

n = input("input a positive integer:")
m = input("input another positive integer, bigger than the first:")
cntr = 1
lst = []
for k in range(n,m+1):
    while k != 1:
        if k%2 ==0:
            k = k/2
            cntr += 1
        elif k%2 != 0 and k!=1:
            k = (3*k)+1
            cntr += 1
    else:
        lst.append(cntr)
        cntr = 1

print max(lst)

2016/01/20 17:13

취미로재미로

  • 입력된 문자열 오류 체크 및 수 제한 범위 판단을 넣었습니다.
  • 제한 범위는 최소 값이 1이 이상이어야 하고, 최대 값을 넘지 말아야 합니다.
  • 짝,홀수 판단은 나머지 연산으로, 그리고 switch문을 통해 추가계산을 하였습니다.
  • 너무 큰수가 들어오면 int 최대수를 넘어가면서 나머지 결과로 0,1 이외의 숫자로 인해 무한무프가 존재하였습니다.
  • 그래서 0 or else 판단이 아닌 0 or 1 or else로 판단하였습니다.
int i, j, n, cycle = 0, maxCycle = 0;

Console.Write("Input Min : ");
if (!int.TryParse(Console.ReadLine(), out i)) return;

Console.Write("Input Max : ");
if (!int.TryParse(Console.ReadLine(), out j)) return;

if (i < 1 || i > j) return;

for (int num = i; num <= j; ++num)
{
    n = num;
    cycle = 1;
    while (n != 1)
    {
        cycle++;
        switch (n % 2)
        {
            case 0: n /= 2; break;
            case 1: n = n * 3 + 1; break;
            default: return;
        }
    }
    if (maxCycle < cycle) maxCycle = cycle;
}
Console.WriteLine("Maximum Cycle : " + maxCycle);

결과

  • Input Min : 1
  • Input Max : 10
  • Maximum Cycle : 20
  • Input Min : 100
  • Input Max : 200
  • Maximum Cycle : 125
  • Input Min : 201
  • Input Max : 210
  • Maximum Cycle : 89
  • Input Min : 900
  • Input Max : 1000
  • Maximum Cycle : 174

2016/01/24 15:28

이 우람

Ruby

seq = ->n { n==1? n : seq[n.odd?? 3*n+1:n/2] + 1 }
max_len = ->ls=$< { ls.map {|_|l=_.split; [l, eval(l*'..').map(&seq).max]*' '} }

Test

expect(seq[22]).to eq 16
#=> for stdin/stdout 
lines = ["1 10", "100 200", "201 210", "900 1000"]
max_seq_lens = ["1 10 20", "100 200 125", "201 210 89", "900 1000 174"]
expect(max_len[lines]) .to eq max_seq_lens

Output

#=> puts max_len[]
1 10
100 200
201 210
900 1000

1 10 20
100 200 125
201 210 89
900 1000 174

2016/01/27 22:17

rk

#include <stdio.h>
#include <stdlib.h>

int getCycle(int num) {
    int len = 1;

    while (num != 1) {
        len++;
        if (num % 2 == 1) {
            num = num * 3 + 1;
        } else {
            num = num / 2;
        }   
    }   

    return len;
}

int main(int argc, char *argv[]) {
    int max = 0;
    int cycle = 0;

    if (argc != 3) {
        printf("Input num\n");
        return -1; 
    }   

    int start_num = atoi(argv[1]);
    int end_num = atoi(argv[2]);

    for (int i=start_num; i<=end_num; i++) {
        cycle = getCycle(i);
        if (cycle > max) {
            max = cycle;
        }   
    }   

    printf(" Max Cycle: [%d]\n", max);

    return 0;
}

2016/02/15 14:17

양승은

#coding: CP949
i = int(input('i를 입력해라:'))
j = int(input('i보다 큰 수를 입력해라:'))
result=[]
for n in range(i,j+1):
    length=[n]
    while n != 1:
        if n % 2 == 1:
            n=3*n+1
        else:
            n=n/2
        length.append(n)
    result.append(len(length))
print(max(result))

파이썬 3.4

2016/02/27 16:34

lovegalois2

while __name__ == '__main__':
    i = int(input('i: '));j = int(input('j: '));li = [];c = 0
    for n in range(i,j+1):
        while 1:
            if n==1:break
            elif n%2==0:n/=2;c+=1
            elif n%2==1:n=n*3+1;c+=1
        li.append(c);c = 0
    print(max(li)+1)

파이썬 3.5.1입니다.

2016/03/14 15:46

Flair Sizz

int longestCycleLength(int x, int y) {
        int max = 0;

        for(int i=x; i<=y; i++) {
            if(max < findCycleLength(i)) {
                max = findCycleLength(i);
            }
        }
        return max;
    }

    private int findCycleLength(int i) {
        int count = 1;

        while(i != 1) {
            if(i%2 == 0) {
                i = i / 2;
                count++;
            }
            else {
                i = (i * 3) + 1;
                count++;
            }
        }
        return count;
    }

java 코드

2016/03/15 02:19

mozzi

livescript 입니다.

main = (i, j) ->
    [i to j].map (n)->
        l = 1
        while n > 1
            n = if n % 2 == 0 then n / 2 else 3 * n + 1
            l += 1
        l
    .reduce (>?), 0

console.log main 1 10
console.log main 100 200
console.log main 201 210
console.log main 900 1000

2016/03/16 12:08

룰루랄라

def maxCycle(a,b) :
    maxCnt=0
    for i in range(a,b+1) :
        preCnt=1
        while(i!=1) :
            if (i%2==0) : 
                i=i/2
            else :
                i=i*3+1
            preCnt+=1
        if (maxCnt<=preCnt) :
            maxCnt = preCnt

    return maxCnt

2016/03/24 10:49

@>---

파이썬3.4입니다. 재귀로 풀었습니다.

def f(n):
    if n == 1:  return 1 
    if n % 2 == 0:  return f(n // 2) + 1
    else:   return f(n * 3 + 1) + 1
    #각각 return의 1은 사이클 길이를 하나씩 카운트한다.

while True:
    i, j = input('i j? ').split()
    print(max([f(n) for n in range(int(i), int(j) + 1)])) #i~j까지 사이클 리스트 중 가장 큰 값을 출력

2016/03/25 00:52

디디

C로 작성해 봤습니다.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    long n = 0;
    long i = 0;
    long j = 0;
    long iter = 1;
    long loop = 0;
    long maxIter = 0;

    if(argc > 2)
    {
        i = atoi(argv[1]);
        j = atoi(argv[2]) + 1;
    }
    else if(argc == 2)
    {
        i = atoi(argv[1]);
        j = atoi(argv[1]) + 1;
    }
    else
    {
        printf("input range i to j\n");
        return 1;
    }

    for(loop = i; loop < j; loop++)
    {
        n = loop;
        while(n != 1)
        {
            //printf("%d ", n);

            if(n % 2 == 0)
                n /= 2;

            else
                n = n * 3 + 1;

            iter++;
        }
        //printf("%d\n", n);
        if(iter > maxIter)
        {
            maxIter = iter;
        }
        iter = 1;
    }

    printf("\n\nMAX ITER: %ld\n", maxIter);
    return 0; 
}

2016/04/07 10:39

황 승태

파이썬3.5.1

def f(n):
    c = 0
    while True:
        if n == 1:
            return c+1
        elif n%2==0:
            n /= 2
            c += 1
        else:
            n = 3*n+1
            c += 1

a,b = map(int,input().split())
res = []
for i in range(a,b+1):
    res.append(f(i))
print(max(res))

'''
INPUT : 1 10
OUTPUT: 20

INPUT : 100 200
OUTPUT: 125

INPUT : 201 210
OUTPUT: 89

INPUT : 900 1000
OUTPUT: 174
'''

2016/04/17 15:45

차우정

Python 3.4.4

def threeNtwo(number, count = 1):
    if number == 1:
        return count

    if number % 2 == 0:
        number = number // 2
    else:
        number = number * 3 + 1

    count = count + 1
    return threeNtwo(number, count)

while True:
    data = list(map(int, input().split()))
    data.append(1)

    for x in range(data[0], data[1] + 1):
        if data[2] < threeNtwo(x):
            data[2] = threeNtwo(x)

    print(data)

2016/05/09 18:43

SanghoSeo

def three(n):
    an=[]
    an.append(n)
    while n!=1:
        if n%2==0:
            n=n/2
            an.append(int(n))
        else:
            n=n*3+1
            an.append(int(n))
    return an

a=input().split(" ")
b=[]
for i in range(int(a[0]),int(a[1])+1):
    b.append(len(three(int(i))))
print(a[0],a[1],max(b))

2016/05/21 00:09

Dr.Choi

파이썬 3.5.1 입니다

def cycle(i,j):
    cycle=[]
    for n in range(i,j+1):
        a=[]
        a.append(n)
        while n>1:
            if n%2==0:
                n=n/2
                a.append(n)
            else:
                n=3*n+1
                a.append(n)
        cycle.append(len(a))
    print(max(cycle))

2016/05/30 09:25

권 준규

C#으로 작성했습니다.


        public int MaxCycle(int i, int j)
        {
            var max = 0;
            while (i <= j)
            {
                var curr = FindCycle(i++);
                max = curr > max ? curr : max;
            }
            return max;
        }

        public int FindCycle(int i)
        {
            var count = 1;
            do
            {
                i = i%2 == 0 ? i/2 : i*3 + 1;
                count++;
            } while (i != 1);
            return count;
        }

2016/05/31 22:06

Straß Böhm Jäger

ㅋㅋㅋ 쉬어가기 문제다! i,j의 범위를 모르지만 너무 크지 않기를 바라면서 ㅋㅋ

#include <iostream> 
#include <cstdio> 
#include <cstdlib> 
#include <algorithm> 
using namespace std;

int cnt(int x){
    int ret = 0; 
    while (x>1){
        if (x%2) x *= 3, x += 1; 
        else x /= 2; 
        ret++;  
    }
    return (ret+1); 
}

int main(){
    int i,j; 
    scanf("%d %d",&i,&j);  
    int maxlen = 0;  
    for (int a = i; a <= j; a++){
        maxlen = max(maxlen,cnt(a)); 
    }
    printf("%d %d %d\n",i,j,maxlen); 
    return 0;  
}   

2016/06/04 15:58

iljimae

#include <stdio.h>

int main(void)
{
    int a, b, i, temp, length, max_length;
    length = 1;
    max_length = 1;
    scanf("%d %d", &a, &b);

    for(i = a; i <= b; i++){
        temp = i;
            while(i>1){
            if(i % 2 == 0) {
                i/=2;
                length++;
            }
            else {
                i = i * 3 + 1;
                length++;
            }
        }
        if(length > max_length){
            max_length = length;
            length = 1;
            i = temp;
        }
        else{
            i = temp;
            length = 1;
        }
    }
    printf("Maximum length: %d\n", max_length);
    return 0;
}

C언어로 작성 했습니다.

2016/06/05 01:53

GyuHo Han

package main

import "fmt"

func CalcCycle(num int) int {
    cycle := 0
    for {
        if num % 2 == 0 {
            num /= 2
        } else {
            num = (num * 3) + 1
        }
        cycle++
        if num == 1 {
            cycle++
            break
        }
    }
    return cycle
}

func main() {
    var min, max int

    fmt.Print("Input Min: ")
    fmt.Scanf("%d", &min)

    fmt.Print("Input Max: ")
    fmt.Scanf("%d", &max)

    max_cycle := 0
    for i := min; i <= max; i++ {
        cycle := CalcCycle(i)
        if cycle > max_cycle {
            max_cycle = cycle
        }
    }
    fmt.Printf("%d %d %d", min, max, max_cycle)
}

2016/06/11 23:59

uuuuuup

Delphi 2010 Memory 사용

procedure TForm4.btn3nplus1ProblemClick(Sender: TObject);
var
  M: array of Integer;

  function Cycle(cc: Integer): Integer;
  var
    k: Integer;
  begin
    if M[cc] > 0 then
      exit(M[cc]);
    k := cc;
    result := 0;
    while true do
    begin
      if k = 1 then
      begin
        M[cc] := result;
        exit(M[cc]);
      end;

      if (k < 1000) and (M[k] > 0) then
      begin
        M[cc] := result + M[k];
        exit(M[cc]);
      end;

      if k mod 2 = 0 then // 짝수면 
        k := k div 2
      else
        k := k * 3 + 1;
      Inc(result);
    end;
  end;

  function MaxCount(n1, n2: Integer; var nMax: Integer): Integer;
  var
    i: Integer;
  begin
    result := 0;
    nMax := 0;
    for i := n1 to n2 do
      if result < M[i] then
      begin
        result := M[i];
        nMax := i;
      end;
  end;

var
  i, j, nCnt, nMax: Integer;
  sFmt: string;
begin
  // 최대 Cycle의 수 구하기 
  SetLength(M, 1000);
  // 데이터 초기화 
  for i := 0 to 1000 do
    M[i] := 0;
  M[1] := 1;
  M[2] := 2; // 2, 1 

  // 1부터 1000까지 모든 수의 최대 사이클 길이를 구함. => M에 저장 
  for i := 3 to 1000 do
    Cycle(i);
  Memo1.Lines.Clear;
  sFmt := 'Range(%d, %d)의 최대 사이클 길이: %d,  숫자: %d';
  Memo1.Lines.Add(format(sFmt, [1, 10, MaxCount(1, 10, nMax), nMax]));
  Memo1.Lines.Add(format(sFmt, [100, 200, MaxCount(100, 200, nMax), nMax]));
  Memo1.Lines.Add(format(sFmt, [201, 210, MaxCount(201, 210, nMax), nMax]));
  Memo1.Lines.Add(format(sFmt, [900, 1000, MaxCount(900, 1000, nMax), nMax]));
end;

2016/07/11 10:48

강 경수

startnum=int(input("start num 입력 : "))
endnum=int(input("end num 입력 : "))
cyclelist=[]
for i in range(startnum,endnum+1):
    cycle=1
    while i!=1:
        if i%2 ==0:
            i = i // 2
            cycle+=1
        else:
            i = i*3 + 1
            cycle+=1
    cyclelist+=[cycle]
print("start : %d , end : %d , cycle : %d"%(startnum,endnum,max(cyclelist)))

Python 3.5.2

2016/07/28 12:42

Zee

늅늅입니다. 좀 무식한 방법이지만, 자바로 풀었습니다.

public static int number;

    public static void main(String args[])
    {
        InsertNumber(1, 10);
        InsertNumber(100, 200);
        InsertNumber(201, 210);
        InsertNumber(900, 1000);
    }

    public static void InsertNumber(int a, int b)
    {
        int numCount = (b+1) -a;

        int[] numbers = new int[numCount];

        for(int i = 0; i < numCount; i++)
        {
            numbers[i] = a+i;
        }

        Prossecing(numbers);
    }

    public static void Prossecing(int[] arrayNum)
    {
        int[] valueCount = new int[arrayNum.length];

        for(int i = 0; i < arrayNum.length; i++)
        {
            number = arrayNum[i];
            valueCount[i] = 1;

            do
            {
                //System.out.print(String.valueOf(number)+" ");

                if(number %2 == 0)
                {
                    number = number/2;
                }
                else
                {
                    number = number*3 +1;

                }

                valueCount[i]++;

            }while(number > 1);
        }

        int largestNumCount = 0;

        for(int i = 0; i < valueCount.length; i++)
        {
            if(largestNumCount < valueCount[i])
            {
                largestNumCount = valueCount[i];
            }
        }

        System.out.println("가장 많은 루프 횟수는 " + largestNumCount + "회 입니다.");
    }

2016/08/02 16:29

여우와향신료

def nPlus(n):
    #print n
    cnt = 1
    while n != 1:
        if n % 2 == 0:
            n /= 2
        else:
            n = n * 3 + 1
        # print n
        cnt += 1
    return cnt

def nPlusMax(inNum):
    numbers = inNum.split()
    count = 0
    for i in range(int(numbers[0]),int(numbers[1])+1):
        if count < nPlus(i):
            count = nPlus(i)
    print inNum + "\t" + str(count)

nPlusMax("1\t10")
nPlusMax("100\t200")
nPlusMax("201\t210")
nPlusMax("900\t1000")


2016/08/05 13:00

kim

def func(n):
    result=1
    while True:
        if n==1:
            return result
        if n%2==0:
            n/=2
        else:
            n=3*n+1
        result+=1
def get(i,j):
    result=0
    for c in range(i,j+1):
        comp=func(c)
        if comp>result:
            result=comp
    return result
i=int(input())
j=int(input())
print(get(i,j))

python 3.5로 작성했습니다.

2016/08/14 13:26

impri

python 3.5.2 증명문제네요.. 좋습니다.

i,j = (201, 210)

def get_cycle_len(num):
    count = 1

    while num != 1:
        num = (num%2==0) and num/2 or num*3 +1
        count+=1

    return count

print(max(get_cycle_len(x) for x in range(i, j+1)))

2016/08/16 22:52

정 우순

#__author__ = 'Admin'
#22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
#def_name = to_the_one, input = integer, output = the length of the cycle, type of the result = the length of the list
# what do I need to solve this problem?
# if the number is even, divide it with number 2
# if the number is odd, multiply it with number 3 and plus 1

def to_the_one(first, last):
    result_of_cycle = []
    for number in range(first,last+1):
        result_list = [number]
        while number <> 1:
            if number % 2 == 0:
                number = number/2
                result_list.append(number)
            else:
                number = 3*number + 1
                result_list.append(number)
        result_of_cycle.append(len(result_list))
    return max(result_of_cycle)


print to_the_one(1,10) # resultt  : 20
print to_the_one(100, 200) # resul : 125
print to_the_one(201, 210) # result : 89
print to_the_one(900,1000) # result : 174

2016/08/18 21:33

Kim Seong Hyeon

public int ThreeNPlusOne(int i, int j)
        {
            int[] CountArray = new int[j - i + 1];
            int Count = 0;
            int CountOrder = 0;
            for (; i <= j; i++)
            {
                int Num = i;
                Count = 0;
                while (Num > 1)
                {
                    if (Num % 2 == 0)
                    {
                        Num /= 2;
                        Count++;
                    }
                    if ((Num % 2 > 0) && (Num > 1))
                    {
                        Num = (Num * 3) + 1;
                        Count++;
                    }
                }
                CountArray[CountOrder] = Count;
                CountOrder++;
            }
            int MaxCount = CountArray.Max() + 1;
            return MaxCount;
         }


왠지 쓸데없이 변수가 많은거같네요 ㅋㅋ

2016/08/28 09:33

이규민

python 2.7


def N_Problem(n1,n2):
    L=[]
    Max=0
    for i in range(n1,n2+1):
        n=i
        count=1
        while(n!=1):
            if(n%2==0):
                n/=2
            else:
                n=(n*3)+1
            count+=1

        L.append(count)
    print"%d %d %d"%(n1,n2,max(L))

N_Problem(1,10)
N_Problem(100,200)
N_Problem(200,210)
N_Problem(900,1000)
N_Problem(1,100000)

****숫자 마다 점검을 해서 리스트에 사이클을 돈 숫자를 리스트에 집어넣고 그중에서 Max 값을 구했습니다

2016/09/08 14:41

leye195

python 2.7

num1 = int(raw_input('input first number: '))
num2 = int(raw_input("input second number: "))

def three_one(n1, n2):
    cycle = []

    for n in range(n1, n2+1):
        temp = []
        while not n == 1:
            temp.append(n)
            if n % 2 == 0:
                n = n / 2
            else:
                n = n * 3 + 1
        cycle.append(len(temp) + 1)

    return max(cycle)

print '{} {} {}'.format(num1, num2, three_one(num1, num2))

2016/09/13 18:54

빠리공원

파이썬입니다.

def Problem_3n(n):
    count = 1
    while n != 1:
        if n%2 == 0:
            n //= 2
            count += 1
        else:
            n = 3*n + 1
            count += 1
    return count

n,m = input().split(' ')
n = int(n); m = int(m)

tmp = 0
for i in range(n,m+1):
    tmp = max(tmp,Problem_3n(i))

print("{} {} {}".format(n,m,tmp))

파이썬 초보입니다. 많은피드백 부탁드립니다!

2016/10/21 07:01

조 우성

#include <iostream>
using namespace std;
int getCycleN(int val);

int main() {
    int inputI, inputJ;
    cin>>inputI>>inputJ;
    int max=0;
    for(int i=inputI;i<=inputJ;i++) {
        if(max<getCycleN(i))
            max = getCycleN(i);
    }
    cout<<max<<"\n";
    return 0;
}

int getCycleN(int val) {
    int count=1;
    while(val!=1) {
        if(val%2==0) {
            val = val/2;
            count++;
        }
        else {
            val = val*3+1;
            count++;
        }
    }
    return count;
}


2016/10/25 15:16

코딩초보

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <string>

using namespace std;
int paul(int, int);

int main(void)

{
    int start, end;
    cin >> start >> end;
    cout << paul(start, end) << endl;

    system("pause");
    return 0;
}
int paul(int start, int end) {
    int count = 1, cycle = 0, init;

    for (int n = start; n <= end; n++) {    //start ~ end
        init = n;   //n 값을 초기화하기위해
        while (true) {
            if (n == 1) {
                break;
            }
            if (n % 2 == 0) {
                n = n / 2;
            }
            else {
                n = (n * 3) + 1;
            }
            count++;
        }
        if (count > cycle) {
            cycle = count;  
        }
        count = 1;
        n= init;    //count 와 n 초기화(while문을 빠져나오면 n은 무조건 1이되므로
    }
    return cycle;   //최대 싸이클 리턴
}

2016/11/03 11:29

개허접

public class ThreeNOne {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int maxCycle = 0;
        int cycle = 0;

        int min = 1;
        int max = 10;

        for (int i = min; i <= max; i++) {
            cycle = getCycle(i);
            if (maxCycle < cycle) {
                maxCycle = cycle;
            }
        }
        System.out.println(min + " " + max + " " + maxCycle);
    }   

    private static int getCycle(int val){
        int cycle = 1;

        while (val != 1) {
            cycle++;
            if (val % 2 == 0) {
                val /= 2;
            }else{
                val *= 3;
                val++;
            }

        }

        return cycle;
    }

}

2016/11/08 18:04

강 우민

st_ptr, end_ptr = 1, 100000
num=0
count, max_count = 0, 0
for i in range(end_ptr,st_ptr-1,-1):
    count=1
    num=i
    while num != 1:
        if num % 2 == 1:
            num = (num * 3) + 1
        else :
            num = num / 2
        count += 1

    if count > max_count:
        max_count = count

print(max_count)

2016/11/19 16:17

바바

Func<int, int> Paul = (k) => {
     int pcnt = 1;
     while (k != 1) {
         k = (k % 2 == 0) ? (k / 2) : (3 * k) + 1;
         pcnt++;
     }
     return pcnt;
};

Func<int, int, int> getMaxCycleCount = (start, end) => {
    return Enumerable.Range(start, (end - start) + 1).Max(k => Paul(k));
};

string inputs = "1 10, 100 200, 201 210, 900 1000";
foreach(var v in inputs.Split(new string[] { "," }, StringSplitOptions.None).Select(k => k.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries))) {
    Console.WriteLine($"{Convert.ToInt32(v[0])}, {Convert.ToInt32(v[1])} => {getMaxCycleCount(Convert.ToInt32(v[0]), Convert.ToInt32(v[1]))}");
}

2016/11/23 15:28

lee jaekyoon

def _3np1(num):
    n = num
    yield int(n)
    while n != 1:        
        if n % 2 == 0:
            n = n / 2
        else:
            n = n * 3 + 1
        yield int(n)

def do(a, b):
    print('{:<6}{:<6}{:<6}'.format(a, b, max([len(list(_3np1(x))) for x in range(a, b + 1)])))

do(1, 10)
do(100, 200)
do(201, 210)
do(900, 1000)

Python 3.5.2에서 작성하였습니다.

2016/11/28 17:16

Yeo HyungGoo

include

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

int main() { int i, x, y, max; scanf("%d %d", &x, &y); max = cycle(y); for (i = x; i < y; i++) { if (max < cycle(i)) max = cycle(i); } printf("%d\n", max); return 0; }

2016/12/21 22:52

리코둔

package PracticePackage;

import java.util.Scanner;

// http://codingdojang.com/scode/409?answer_mode=hide

public class threen {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        //입력받은 두숫자
        int n1 = 0;
        int n2 = 0;

        //두숫자를 비교하여 다시 변수에 담음
        int big = 0;
        int small = 0;

        //배열의 총 크기
        int Arrangement = 0;

        //사이클
        int cycle = 0;
        int total = 0;

        System.out.println("첫번째 숫자를 입력해 주세요.");
        n1 = sc.nextInt();

        System.out.println("두번째 숫자를 입력해 주세요.");
        n2 = sc.nextInt();

        if(n1 > n2) {
            big = n1;
            small = n2;
        } else if(n2 > n1){
            big = n2;
            small = n1;
        }

        Arrangement = big - small;

        int[] number = new int[Arrangement + 1];

        int j = 0;
        for(int i = small; i < Arrangement + 2; i++) {
            number[j] = i;
            j++;
        }

        for(int i = 0; i < number.length; i++) {
            if(number[i] != 0) {
            while (true) {

                //짝수,홀수처리
                if(number[i]%2 == 0) {
                    number[i] = number[i]/2;
                    cycle++;
                } else {
                    number[i] = number[i] * 3 + 1;
                    cycle++;
                }
                if(number[i] == 1) {
                     if(total < cycle) {
                         total = cycle;
                         cycle = 0;
                         break;
                     }
                     cycle = 0;
                     break;
                }
             }
           }
        }

        System.out.println("첫번쨰 입력 숫자 :" + n1);
        System.out.println("두번쨰 입력 숫자 :" + n2);

        System.out.println("두 숫자사이의 최대 사이클 크기 :" + cycle);
    }

}

2016/12/26 17:24

Lee Juu

list_ = [[1,10],[100,200],[201,210],[900,1000]]
for x in range(len(list_)):
    c_len = list()
    for y in range(list_[x][0],list_[x][1]+1):
        result = list()
        result.append(y)
        while y != 1:
            if y % 2 == 0:
                y = y//2
            else:
                y = y*3+1
            result.append(y)
        c_len.append(len(result))
    print(list_[x][0],list_[x][1],max(c_len))

#### 2016.12.29 D-420 ####

2016/12/29 23:02

GunBang

$input = array(array(1,10), array(100,200), array(201,210), array(900,1000));

foreach($input as $nums){
    $results =  array_map("cb", range($nums[0],$nums[1]));
    echo sprintf("%s\t%s\t%s\n",$nums[0],$nums[1],max($results));
}

function cb($input){
    $result = array();
    $result[] = $input;
    while(true){
        $input = ($input%2 ==0) ? $input/2 : ($input*3)+1;
        $result[] = $input;
        if($input == 1) return count($result);
    }
}

2017/01/05 09:33

stardust

static int cycle = 0;
    static int START = 100;
    static int END = 200;

    static int MAX_CYCLE = 0;

    public static void main(String argv[]) throws Exception {


        for(int i=START; i<=END ; i++){

            int temp = getCycle(i);
            if(MAX_CYCLE < temp){
                MAX_CYCLE = temp;
            }
        }

        System.out.println(MAX_CYCLE);
    }


    private static int getCycle(int num){

        if(num == 1){
            return 1;
        }else{
            if(num%2 == 1)
                return getCycle(num*3+1) +1;
            else
                return getCycle(num/2) +1;

        }

    }

2017/01/18 13:51

lhc


    static int nCycle = 0;
    static int maxCycle = 0;

    public static void main(String[] args) {

        maxCycle(1, 10);
        maxCycle(100, 200);
        maxCycle(201, 210);
        maxCycle(900, 1000);
    }

    private static void maxCycle(int start, int end) {
        for (int i = start; i <= end; i++) {
            nCycle = 0;
            getCycle(i);
            if (nCycle > maxCycle) maxCycle = nCycle;
        }
        System.out.println(start + "\t" + end + "\t" + maxCycle);
        maxCycle = 0;
    }

    private static void getCycle(int number) {
        nCycle ++;
        if (number == 1) return;

        if (number % 2 == 0) {
            getCycle(number / 2);
        } else {
            getCycle(number * 3 + 1);
        }
    }

1   10  20
100 200 125
201 210 89
900 1000    174

2017/02/10 15:58

김경수

파이썬 2.7과 numpy 이용하였습니다.

import numpy as np

i, j = raw_input('?').split()

n = list()
count = 1

for k in range(int(i), int(j)+1):
    n.append(k)     
    while(n[-1] != 1):
        if n[-1] % 2 == 0:
            n.append(n[-1]/2)
        else:
            n.append(n[-1]*3 + 1)
    count = np.maximum(count, len(n))
    n = []

print count

2017/02/13 22:04

조현우

def seq(n):
    x = [n]
    while n != 1:
        if n%2 == 0:
            n = int(n/2)
            x.append(n)
        else:
            n = int(3*n+1)
            x.append(n)
    return len(x)

def cycle(i, j):
    cyList = []
    for x in range(i,j+1):
        cyList.append(seq(x))
    return i, j, max(cyList)

2017/02/18 21:52

wbpark

def paul(n):
    m=1
    while n!=1:   
        if n==1:
            break
        elif n%2==0:
            n=n/2
        else:
            n=3*n+1
        m+=1
    return m

def max_cycle(data):
    for i in data:
        print(i[0], i[1], max(paul(k) for k in range(i[0],i[1]+1)))
max_cycle([[1,10],[100,200],[201,210],[900,1000]])

2017/02/20 00:19

김구경

자기전에 심심해서 풀어봤어요

c++

#include <iostream>
using namespace std;
int CalCycle(int value);
int CalMaxCycle(int min, int max);

void main() 
{
    cout << CalMaxCycle(900,1000) << endl;
}

int CalMaxCycle(int min,int max)
{
    int maxValue = 0;
    for(int i=min;i<max+1;i++)
    {
        int calvalue = CalCycle(i);
        if(maxValue<calvalue)
        {
            maxValue = calvalue;
        }
    }

    return maxValue;
}
int CalCycle(int value) 
{
    int count = 1;
    int num = value;
    while(num !=1)
    {
        //짝수
        if(num%2==0)
        {
            num = num / 2;
        }
        //홀수
        else
        {
            num = num * 3 + 1;
        }
        count++;
    }

    return count;
}

2017/02/22 07:43

박용진

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ThreeN1Problem {
    public static void main(String[] args) throws FileNotFoundException {

        String path = ThreeN1Problem.class.getResource("").getPath();
        Scanner sc = new Scanner(new File(path + "ThreeN1Problem.txt"));
        Integer numbers[][] = new Integer[10][2];

        int i = 0;
        while (sc.hasNext()) {
            numbers[i][0] = sc.nextInt();
            numbers[i][1] = sc.nextInt();
            i++;
        }

        for (int j = 0; j < i; j++) {
            int max = 0;
            for (int k = numbers[j][0]; k <= numbers[j][1]; k++) {
                int count = 1;
                int n = k;
                while (n > 1) {
                    if (n % 2 == 0) {
                        n = n / 2;
                    } else {
                        n = n * 3 + 1;
                    }
                    count++;
                }
                if (max < count) max = count;
            }
            System.out.printf("%d\t\t%d\t\t%d\n", numbers[j][0], numbers[j][1], max);
        }
    }
}

2017/03/03 13:54

genius.choi

Python 3.6.0 입니다

def cycle(num):
    if num==1:
        return 1
    else:
        sequence=[]
        sequence.append(num)
        while num!=1:
            if num%2==0:
                num/=2
            else:
                num=num*3+1
            sequence.append(num)
        return len(sequence)

while 1:
    input_str=input()
    input_list=input_str.split(' ')
    if len(input_list)!=2:
        print('please input two numbers with a single spacer')
        break
    input_list_int=list(map(lambda x:int(x),input_list))
    print('{0} {1} {2}'.format(input_list_int[0],input_list_int[1],max(map(cycle,range(input_list_int[0],input_list_int[1]+1)))))

2017/03/31 12:28

c0din9

package training;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * 어떤 정수 n에서 시작해, n이 짝수면 2로 나누고, 홀수면 3을 곱한 다음 1을 더한다. 
 * 이렇게 해서 새로 만들어진 숫자를 n으로 놓고, n=1 이 될때까지 같은 작업을 계속 반복한다. 
 * 예를 들어, n=22이면 다음과 같은 수열이 만들어진다.
 * 
 * 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
 * n이라는 값이 입력되었을때 1이 나올때까지 만들어진 수의 개수(1을 포함)를 n의 사이클 길이라고 한다. 
 * 위에 있는 수열을 예로 들면 22의 사이클 길이는 16이다. 
 * i와 j라는 두개의 수가 주어졌을때, i와 j사이의 모든 수(i, j포함)에 대해 최대 사이클 길이를 구하라.
 *
 */
public class PatternTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.print("Please insert Number 1? ");
        int iNum1 = sc.nextInt();
        System.out.print("Please insert Number 2? ");
        int iNum2 = sc.nextInt();

        int iMax = 0;
        int iNow = 0;

        for(int i=iNum1;i<iNum2;i++){
            iNow = getCycleNum(i);
            if(iNow > iMax){
                iMax = iNow;
            }
        }
        System.out.println(iMax);

    }

    public static int getCycleNum(int iNum) {
        ArrayList<Integer> arr = new ArrayList();
        if(arr.size() == 0){
            arr.add(iNum);
        }

        while(arr.get(arr.size()-1) != 1){
            if(arr.get(arr.size()-1) % 2 == 0){ // 짝수
                arr.add(arr.get(arr.size()-1)/2);
            } else { // 홀수
                arr.add(arr.get(arr.size()-1)*3+1);
            }
        }

        return arr.size();
    }
}

2017/04/09 19:33

acedo

def n(a,b):
    result = []
    for i in range(a,b+1):
        k=0
        while i>1:
            if i%2==0 and i>1:
                i=i/2
                if i>=1:
                    k=k+1
            if i%2!=0 and i>1:
                i=i*3+1
                if i>=1:
                    k=k+1
        result.append(k)
    return(max(result)+1)

print(n(1,10))
print(n(100,200))
print(n(201,210))
print(n(900,1000))

2017/04/18 13:08

조현

private static int problem3n1(int low, int high){
        if(low > high){
            int temp = low;
            low = high;
            high = temp;
        }

        int max = 0;

        for(int i=low; i<=high; i++){
            int cnt = 1;
            int n = i;

            while(n!=1){
                if(n%2==0){
                    n = n / 2;
                }else{
                    n = 3 * n + 1;
                }
                cnt++;
            }

            if(cnt > max){
                max = cnt;
            }

        }

        return max;
    }

2017/05/03 15:15

yh

def len_array(n):
    lst=[n]
    while n!=1:
        if n%2==0:
            n = n//2
            lst.append(n)
        else:
            n = (n*3)+1
            lst.append(n)
    return len(lst)

def sum_len(i,j):
    lst=[]
    for i in range(i, j+1):
        n=len_array(i)
        lst.append(n)
    return lst

result=max(sum_len(1,10))
print(" 1      10    %d" % result)
result=max(sum_len(100,200))
print("100    200   %d" % result)
result=max(sum_len(201,210))
print("201    210    %d" % result)
result=max(sum_len(900,1000))
print("900   1000   %d" % result)

2017/05/15 01:30

정세진

public static void main(String args[]) {
        // 입력값 n1,n2 최대값 max 갯수 cnt
        Scanner s = new Scanner(System.in);
        int n1 = s.nextInt();
        int n2 = s.nextInt();
        int max=0;
        for (int i = n1; i <= n2; i++) {
            int cnt = 1;
            int n = i;
            while(n != 1) {
                if (n % 2 == 0) {// n이 짝수일 경우
                    n /= 2;
                } else {// n이 홀수 일 경우
                    n = (n * 3) + 1;
                }
                cnt++;
            }
            if(cnt>max)
                max=cnt;
        }
        System.out.println(max);
    }

2017/05/17 14:59

김재인

#include <stdio.h>

int makeOne(int n){ 
    int count = 1;  
    while(n != 1){  
        if(n%2 == 0)
            n = n/2;
        else
            n = n*3 + 1;
        count++;
    }
    return count;
}

int main(void){ 
    int min,max;
    int i,len;
    int maxN,maxLen=0;

    printf("Please input two sorted numbers.\n");
    scanf("%d %d",&min,&max);

    for(i = min;i<max+1;i++){
        len = makeOne(i);
        if(len>maxLen){
            maxLen = len;
            maxN = i;
        }
    }
        printf("%d",maxLen);
}

입출력예시 말인데요 설마 임의의 갯수의 숫자쌍을 받아서 처리하는건가요? 그건 어떤식으로 하는거지...

2017/06/02 12:15

Gunhee Jo

python 3.6 simple method.

def find_cycle_of_n(n):
    cnt = 1
    while n != 1:
        if n % 2 == 0: next_n = n/2
        else: next_n = 3*n + 1
        cnt +=1
        n = next_n
    return cnt


lines = []
while True:
    line = input()
    if line: lines.append(line)
    else: break


1    10
100  200
201  210
900  1000

for line in lines:
    x, y = map(int, line.split())
    print("{}\t{}\t{}".format(x, y, max(find_cycle_of_n(i) for i in range(x,y+1))))


1   10  20
100 200 125
201 210 89
900 1000    174

2017/06/11 07:40

예강효빠

def function(n):
    num_arr=[]
    num_arr.append(n)
    while n!=1:
        #짝수
        if n%2==0:
            n=n/2
            num_arr.append(n)
        else:
            n=3*n+1
            num_arr.append(n)
    return len(num_arr)
def find_max_arr(n,m):

    max_arr=[]
    while n<=m:
        max_arr.append(function(n))
        n+=1
    max_value=max_arr[0]
    for i in range(len(max_arr)):
        if max_arr[i]>max_value:
            max_value=max_arr[i]
    return max_value

while True:
    n,m=input().split()
    m=int(m)
    n=int(n)
    if m==0 and n==0:
        print("finish")
        break
    else:
        print ( n,m,find_max_arr(n,m))

2017/06/13 20:07

나후승

javascript(ES6)

var getRange = (a, b) => Array.from(Array(b - a + 1), (v, i) => a + i)
var max = (a, b) => Math.max(a, b);
var cycle = n => n === 1 ? 1 : n % 2 === 0 ? cycle(n / 2) + 1 : cycle(3 * n + 1) + 1;
var maxcycle = (a, b) => getRange(a, b).map(cycle).reduce(max);

console.log(maxcycle(1,     10));
console.log(maxcycle(100,  200));
console.log(maxcycle(201,  210));
console.log(maxcycle(900, 1000));

2017/06/15 16:08

funnystyle

// 3n+1 - C#
using System;
using System.Collections.Generic;
namespace _3nplus1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Ready>>>");
            List<int[]> cases = new List<int[]>(); int len = 0;
            while (true)
            {
                string input = Console.ReadLine();
                try
                {
                    int[] item = { int.Parse(input.Split('\t')[0]), int.Parse(input.Split('\t')[1]) };
                    cases.Add(item);
                    len++;
                }
                catch{ break; }
            }
            List<int> result = new List<int>();
            foreach(int[] c in cases)
            {
                int max = 1;
                for (int i = c[0]; i <= c[1]; i++)
                {
                    int t = i, att = 1;
                    while(t != 1)
                    {
                        if (t % 2 == 0)
                            t /= 2;
                        else
                            t = t * 3 + 1;
                        att++;
                    }
                    if (max < att)
                        max = att;
                }
                result.Add(max);
            }
            for (int i = 0; i < len; i++)
                Console.WriteLine("{0}\t{1}\t{2}", cases[i][0], cases[i][1], result[i]);
        }
    }
}

2017/07/07 01:14

Jeong Hoon Lee

start_num = int(input("input bigin number: "))
end_num = int(input("input end number: "))
cycle_list = []
for x in range(start_num,end_num+1):
    temp_num = []
    temp_num.append(x)
    while x != 1:
        if x % 2 == 0:
            x = int(x / 2)
            temp_num.append(x)
        else:
            x = int(x * 3) + 1
            temp_num.append(x)
    cycle_list.append(int(len(temp_num)))
    cycle_list = sorted(cycle_list)
print(start_num, end_num, cycle_list[-1])

지적해주세요

2017/07/17 15:22

이기현

#include <stdio.h>

int totalCycle(int);
void maxCycle(int, int);

int main()
{
    int start, end;
    scanf("%d %d", &start, &end);
    maxCycle(start, end);
    return 0;
}

int totalCycle(int num)
{
    int cnt = 1;
    while (num != 1) {
        cnt++;
        if (num % 2 == 0)
            num >>= 1;
        else
            num = 3 * num + 1;
    }

    return cnt;
}

void maxCycle(int start, int end)
{
    int i,max=0;

    for (i = start; i <= end; i++) {
        if (totalCycle(i) > max)
            max = totalCycle(i);
    }
    printf("%d %d %d\n",start, end, max);
}

2017/07/20 14:17

정동건

C#

using static System.Console;

class Cycle
{
    private int length;
    public int Length => this.length;

    public Cycle(int n)
    {
        length = 1;
        while (n > 1)
        {
            if (n % 2 == 0)
            {
                n = n / 2;
            }
            else
            {
                n = 3 * n + 1;
            }
            length++;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        string input = "1 10\n100 200\n201 210\n900 1000";
        foreach (string line in input.Split('\n'))
        {
            int start = int.Parse(line.Split()[0]);
            int end = int.Parse(line.Split()[1]);

            int maxCycleLength = 0;
            for (int i = start; i <= end; i++)
            {
                int cycleLength = (new Cycle(i)).Length;
                if (maxCycleLength < cycleLength)
                {
                    maxCycleLength = cycleLength;
                }
            }
            WriteLine("{0} {1} {2}", start, end, maxCycleLength);
        }
    }
}

2017/07/20 18:08

Noname

package java_tutorial;

import java.util.Scanner;

public class Cycle_Length {

    public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);

            int from_Num = sc.nextInt();
            int to_Num = sc.nextInt();
            int length = 1;
            int max_Length = 0;
            int new_Num = 0;

            for(int i = from_Num; i <= to_Num; i++)
            {
                    new_Num = i;
                    while(new_Num != 1)
                    {


                            if(new_Num%2==0)
                            {
                                new_Num = new_Num/2;
                            }
                            else
                            {
                                new_Num = new_Num*3+1;
                            }
                            length++;
                    }
                    if(length >= max_Length)
                    {
                            max_Length = length;
                    }
                    length = 1;
            }

            System.out.println(from_Num + "\t" + to_Num + "\t" + max_Length);
    }

}

2017/07/20 18:48

최원석

#include<stdio.h>

int CycleCount(int num);

int main(void)
{
    int num1, num2;
    int i, result;
    int min, max;
    int cnt_max = 0;
    scanf("%d %d", &num1, &num2);
    min = num1 <= num2 ? num1 : num2;
    max = num1 > num2 ? num1 : num2;
    for (i = min; i <= max; i++)
    {
        if (cnt_max < CycleCount(i))
            cnt_max = CycleCount(i); 
    }
    printf("%d\n", cnt_max);
    return 0;
}

int CycleCount(int num)
{
    int cnt = 1;
    while (1)
    {
        if (num % 2 == 0)
        {
            num = num / 2;
            cnt += 1;
        }
        else if (num % 2 == 1 && num != 1)
        {
            num = num * 3 + 1;
            cnt += 1;
        }
        else
        {
            break;
        }
    }
    return cnt;
}

2017/07/23 23:54

MAKESOME

def task(x):
    length = 1
    while x != 1:
        if x%2 == 0:
            x = x / 2
            length += 1
        else:
            x = x * 3 + 1
            length += 1

    return length            

def judge(i,j):
    l = range(i+1, j)
    l2 = [task(x) for x in l]
    print max(l2)


a,b = map(int,raw_input().split(' '))
c,d = map(int,raw_input().split(' '))
e,f = map(int,raw_input().split(' '))
g,h = map(int,raw_input().split(' '))

print "you input :", a, b
print "you input :", c, d
print "you input :", e, f
print "you input :", g, h


judge(a,b)
judge(c,d)
judge(e,f)
judge(g,h)

2017/07/30 23:48

Alberto Yeo

import java.util.*;

public class Problem3nplus1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        int j = sc.nextInt();
        int n, cnt, max=0;

        for(int k=i; k<=j; k++)
        {
            cnt = 1;
            n=k;
            while(n!=1) {
                if(n%2==0) n /= 2;
                else n = n*3+1;
                cnt++;
            }
            if(cnt>max) max=cnt;
        }

        System.out.println(max);
    }
}

2017/07/31 12:15

곽철이

def func(num):
    print(num)
    if num == 1:
        pass
    elif num % 2 == 0:
        num //= 2
        return func(num)
    elif num % 2 != 0:
        num = 3 * num + 1
        return func(num)

파이썬 3.6.2 재귀함수로풀엇습니다

2017/08/05 02:44

시간의마법

[Python 3.6] 성능향상을 위해 이미 계산된 싸이클 길이는 메모리에 저장 및 활용

mem = {1:1}

def findCyclePath(num):
    notFoundCyclePathArray = []
    result = 0;
    while(True):
        if(num in mem.keys()):
            result += mem[num]
            for i, val in enumerate(notFoundCyclePathArray): mem[val] = result - i
            return result
        else:
            notFoundCyclePathArray.append(num)
            if(num % 2 == 0): num = num / 2
            else: num = num * 3 + 1
            result += 1

def findMaxCyclePath(inputVal):
    return max(map(findCyclePath, (num for num in range(inputVal[0], inputVal[1] + 1))))

inputVal = (900, 1000)
print(findMaxCyclePath(inputVal))

2017/08/05 10:27

Eliya

# 사이클 과정에서 나온 모든 결과들을 리스트로 반환하는 함수
def cycle(n) :  # type(n) == int

    cyclilist = [n]
    while True :

        if n == 1 :  # n이 1이 되면 루프 종료
            break

        elif n % 2 == 0 :
            n = n/2
            cyclilist.append(int(n))
            continue

        elif n % 2 == 1 :
            n = 3*n + 1
            cyclilist.append(int(n))
            continue

    return cyclilist


# 두 수를 입력받아서 그 범위 안에 있는 사이클 길이 중 최대값을 반환하는 함수
def max_cycle_length() :

    a = int(input("range starts from : "))  # 범위의 시작
    b = int(input("range ends at : "))  # 범위의 끝
    s = []  # 사이클 길이를 모아놓은 리스트

    for i in range(a, b+1) :
        s.append(len(cycle(i)))

    return max(s)  # 사이클 길이를 모아놓은 리스트에서 최대값을 출력

# 최종 결과
print(max_cycle_length())

2017/08/06 19:28

다크엔젤

  1. 파이썬 3.4입니다
def x3nplus1(n):
    if isinstance(n,int) and n>=1:
        span = 0
        hub = n
        while hub!=1:
            if hub%2==0:
                    hub = int(hub/2) #float방지
            else:
                hub = 3*hub+1
            span += 1
        return span
    else:
        print('x3nplus1 function must have a domain with integer over 0')

result = []
for i in range(int(input()),int(input())+1):
    result.append(x3nplus1(i))
print(max(result))

2017/08/14 13:58

고든

def result(n1, n2):
    a = []
    for num in range(n1, n2+1):
        a.append(getTot(num))
    print(n1, n2, max(a))

def getTot(num):
    tmp = num
    a = [tmp]
    while tmp > 1:
        if tmp % 2 == 0:
            tmp = tmp/2
        else:
            tmp = (tmp * 3) + 1
        a.append(tmp)

    return len(a)


result(1, 10)
result(100, 200)
result(201, 210)
result(900, 1000)

2017/08/22 16:26

piko

def length(x): leng=1 while(True): if(x%2==0): x=x/2 else: x=3*x+1 leng=leng+1 if(x==1): break return leng a=input() b=a.split() m=0 for i in range(int(b[0]),int(b[1])+1): g=length(i) if g>m: m=g print(m) python 3.5

2017/08/27 15:01

impri

public class Ex8 {
    public static void main(String[] args) {
        cycleMax(1,10);
        cycleMax(100,200);
        cycleMax(201,210);
        cycleMax(900,1000);
    }

    public static void cycleMax(int start, int end) {
        int count = 1, max = 0,temp = start; 
        for(int i=start;i<end+1;i++) {
            count = 1;
            int number = i;
            while(true) {
                if(number%2 == 0)   number = number/2;
                else    number = (number*3) + 1;

                count++;
                if(number == 1) break;
            }
            if(max < count) max = count;
        }

        System.out.println(temp + "\t" + end + "\t" + max);
    }
}

2017/09/08 17:05

염현우

# python 3.6
def cycle_len(inp):
    n = inp
    count = 1
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
        count += 1
    return count


inp = list(map(int, input().split()))
rst = list()
for i in range(inp[0], inp[1] + 1):
    rst.append(cycle_len(i))
print(inp[0], inp[1], max(rst))

2017/09/11 12:41

mohenjo

#include <iostream>
#include <vector>
#include <stack>
#include <math.h>
#include <Windows.h>
using namespace std;

int cycle_len(int num) {
    int count = 1;
    while (1) {
        if (num % 2 == 0) {
            num = num / 2;
            count++;
        }
        else if (num == 1) {
            break;
        }
        else {
            num = (num * 3) + 1;
            count++;
        }
    }
    return count;
}


int main() {
    int num = 0;
    int num2 = 0;
    cout << "type numbers : ";
    cin >> num;
    cin >> num2;
    cout << endl;

    int max_cycle_len = 0;

    for (int i = num; i <= num2; i++) if (cycle_len(i) > max_cycle_len) max_cycle_len = cycle_len(i);

    cout << max_cycle_len << endl;

    return 0;
}

2017/09/20 18:03

김기훈

oneInput = int(input())
twoInput = int(input())
number = 0
counts = []
count = 0

for num in range(oneInput, twoInput+1):

 counts.append(count)
 count = 1

 while num != 1:
  if num % 2 == 0:
   num = num / 2
   count = count + 1

  else:
   num = num*3 + 1
   count = count + 1

print(max(counts))

2017/09/20 18:46

rlaxorwn12

자바 입니다.

public class exxx {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int a = scan.nextInt();
        int b = scan.nextInt();
        int max =0;

        for(int i=a; i<=b;i++){
            if(create_num(i)>max){
                max = create_num(i);
            }
        }
        System.out.println(max);

    }
    static int create_num(int num){

        int cnt = 1;
        while(num != 1){
            if(num%2==0) num=num/2;
            else if(num%2==1) num=num*3+1;

            cnt++;
        }
        return cnt;
    }
}

2017/09/27 09:14

김문수

package codingdojang;

public class ex23 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int n = 22;
    while(n != 1) {
        System.out.print(n+ " ");
        if(n%2 == 0) {
            n /= 2;
        }
        else {
            n = 3*n + 1;
        }
    }
    System.out.print(1);
}

}

2017/09/29 11:57

이병호

저는 우선 while문을 사용하여 일반적인 사이클을 구하는 함수를 만들었습니다. 그 후 사이클 중에 가장 큰 사이클을 구하는 함수를 설정했습니다. 이 함수는 시작하는 수에서 끝나는 수까지 각각 cycletime을 구하여 리스트로 만들고, max함수를 이용하여 리스트에서 가장 큰 값을 찾는 식으로 최대 사이클을 찾게 됩니다.

def cycletime(number):
    count = 0 
    while number > 1:
        count += 1
        if number%2 == 0:
            number = number/2
        else:
            number = 3*number+1
    else:
        count += 1
    return count

def maxcycletime(start, end):
    list_cycletime = []
    for i in range(start, end+1):
        list_cycletime.append(cycletime(i))
    return max(list_cycletime)

2017/10/18 00:27

정재훈

저는 우선 while문을 사용하여 일반적인 사이클을 구하는 함수를 만들었습니다. 그 후 사이클 중에 가장 큰 사이클을 구하는 함수를 설정했습니다. 이 함수는 시작하는 수에서 끝나는 수까지 각각 cycletime을 구하여 리스트로 만들고, max함수를 이용하여 리스트에서 가장 큰 값을 찾는 식으로 최대 사이클을 찾게 됩니다.

def cycletime(number):
    count = 0 
    while number > 1:
        count += 1
        if number%2 == 0:
            number = number/2
        else:
            number = 3*number+1
    else:
        count += 1
    return count

def maxcycletime(start, end):
    list_cycletime = []
    for i in range(start, end+1):
        list_cycletime.append(cycletime(i))
    return max(list_cycletime)

2017/10/18 00:29

정재훈

저는 우선 while문을 사용하여 일반적인 사이클을 구하는 함수를 만들었습니다. 그 후 사이클 중에 가장 큰 사이클을 구하는 함수를 설정했습니다. 이 함수는 시작하는 수에서 끝나는 수까지 각각 cycletime을 구하여 리스트로 만들고, max함수를 이용하여 리스트에서 가장 큰 값을 찾는 식으로 최대 사이클을 찾게 됩니다.

def cycletime(number):
    count = 0 
    while number > 1:
        count += 1
        if number%2 == 0:
            number = number/2
        else:
            number = 3*number+1
    else:
        count += 1
    return count

def maxcycletime(start, end):
    list_cycletime = []
    for i in range(start, end+1):
        list_cycletime.append(cycletime(i))
    return max(list_cycletime)

2017/10/18 00:30

정재훈

저는 우선 while문을 사용하여 일반적인 사이클을 구하는 함수를 만들었습니다. 그 후 사이클 중에 가장 큰 사이클을 구하는 함수를 설정했습니다. 이 함수는 시작하는 수에서 끝나는 수까지 각각 cycletime을 구하여 리스트로 만들고, max함수를 이용하여 리스트에서 가장 큰 값을 찾는 식으로 최대 사이클을 찾게 됩니다.

def cycletime(number):
    count = 0 
    while number > 1:
        count += 1
        if number%2 == 0:
            number = number/2
        else:
            number = 3*number+1
    else:
        count += 1
    return count

def maxcycletime(start, end):
    list_cycletime = []
    for i in range(start, end+1):
        list_cycletime.append(cycletime(i))
    return max(list_cycletime)

2017/10/18 00:30

정재훈

저는 우선 while문을 사용하여 일반적인 사이클을 구하는 함수를 만들었습니다. 그 후 사이클 중에 가장 큰 사이클을 구하는 함수를 설정했습니다. 이 함수는 시작하는 수에서 끝나는 수까지 각각 cycletime을 구하여 리스트로 만들고, max함수를 이용하여 리스트에서 가장 큰 값을 찾는 식으로 최대 사이클을 찾게 됩니다.

def cycletime(number):
    count = 0 
    while number > 1:
        count += 1
        if number%2 == 0:
            number = number/2
        else:
            number = 3*number+1
    else:
        count += 1
    return count

def maxcycletime(start, end):
    list_cycletime = []
    for i in range(start, end+1):
        list_cycletime.append(cycletime(i))
    return max(list_cycletime)

2017/10/18 00:36

정재훈

    public static int getMaximumCycle(int i, int j)
    {
        if(i > j)
            return -1;

        int mc = getSequenceCount(i);
        for(int c = i+1; c <= j; c++)
        {
            int currentmc = getSequenceCount(c);
            if(mc < currentmc)
                mc = currentmc;
        }
        return mc;
    }

    public static int getSequenceCount(int n)
    {
        int count = 1;
        while(n != 1)
        {
            if(n%2 == 0)
            {
                n = n / 2;
            }
            else 
            {
                n = (n*3) + 1;
            }
            count += 1;
        }
        return count;
    }

2017/10/24 12:30

김홍규

# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3)
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')

# 어떤 정수 n에서 시작해, n이 짝수면 2로 나누고, 홀수면 3을 곱한 다음 1을 더한다.
# 이렇게 해서 새로 만들어진 숫자를 n으로 놓고, n=1 이 될때까지 같은 작업을 계속 반복한다.
# 예를 들어, n=22이면 다음과 같은 수열이 만들어진다.
# 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
# n이라는 값이 입력되었을때 1이 나올때까지 만들어진 수의 개수(1을 포함)를 n의 사이클 길이라고 한다.
# 위에 있는 수열을 예로 들면 22의 사이클 길이는 16이다.
# i와 j라는 두개의 수가 주어졌을때, i와 j사이의 모든 수(i, j포함)에 대해 최대 사이클 길이를 구하라.
# > 입력 예
# 1    10
# 100  200
# 201  210
# 900  1000
# > 출력 예
# 1    10    20
# 100  200   125
# 201  210   89
# 900  1000  174

number_input = input("from n1 to n2 : ").split()
number = [int(x) for x in number_input]

max = 1
for n in range(number[0], number[1]):
    x = n
    n_series = [x]
    while x is not 1:
        if x % 2:
            x = x * 3 + 1
        else:
            x = x // 2
        n_series.append(x)
    print(n, n_series, len(n_series))
    if max < len(n_series):
        max = len(n_series)

print("=====\n", number[0], number[1], max)

2017/11/07 13:36

Jace Alan

# i~j 까지의 각 숫자들의 list을 구함 -> list길이 구함 -> 수열길이 최대값 찾기

def make_lst(input):
    n = int(input)
    lst = []
    while n > 1 :
    # for i in range(10):
        if n%2 == 1:
            n = n*3+1
            lst.append(n)
        else:
            n = n/2
            lst.append(n)
    lst.append(n)
    return lst

check_len = lambda lst : len(lst)

def value_go(a,b):
    max_n_lst = []
    for i in range(a,b+1):
        max_n_lst.append(check_len(make_lst(i)))
    return max(max_n_lst)

print(value_go(900,1000))

2017/11/12 19:04

정진환

python 3.5 버전입니다

def process(n): 
    if n%2 ==0 : n = n/2 
    elif n%2 ==1 : n = 3*n+1 return(n)

def how_long(n):
    n_list =[]
    while True:
        n_list.append(n) 
        n = process(n)
        if n==1 : break 
    return(len(n_list)+1)

i = input()
j = input()
max([how_long(num) for num in range(int(i), int(j)+1)])

2017/11/17 19:53

Seohyun Choi

i, j= raw_input("enter two numbers: ").split()

i=int(i)
j=int(j)
max_cycle=0
for n in range(i,j+1):
    icycle=1
    while n != 1:
        if n%2 == 0:
            n=n/2
        else:
            n=n*3+1
        icycle=icycle+1
    if icycle > max_cycle:
        max_cycle=icycle
print i, j, max_cycle

2017/12/03 21:58

영이

#include <stdio.h>
void change(int a, int b)
{
    int d[10001],i, e, c, j= -1;
    for(i=a;i<=b;i++)
    {
        c=1;
        e=i;
        for(;;)
        {
            if(e==1)break;
            c++;
            if(e%2==1)e=e*3+1;
            else e=e/2;
        }
        d[i]=c;
    }
    for(i=a;i<=b;i++)
    {
        if(d[i]>j) j=d[i];
    }
    for(i=a;i<=b;i++)
    {
        if(j==d[i])break;
    }
    printf("%d",j);
}
int main()
{
   int a,b;
   scanf("%d %d",&a,&b);
   spy(a,b);
}

2017/12/05 13:15

떼디

def make1(tup):
    x,y=tup
    result=0
    for i in range(x, y+1):
        tmp=1
        while i!=1:
            if not i%2: i/=2
            else: i=i*3+1
            tmp+=1
        if tmp>result:
            result=tmp
    return(result)

nums=tuple(map(int, input().split()))
print(nums[0], nums[1], make1(nums))

2017/12/13 16:44

빗나감

Recursive function 활용

def cal(n,cnt=0):
    cnt+=1
    if n%2 ==0 :
        cnt=cal(n/2,cnt)
    elif n==1 :
        return cnt         
    else :
        n = n*3+1        
        cnt=cal(n,cnt)
    return cnt

lst =[]
print("please two num")
a1 = int(input())
a2 = int(input())
for i in range(a1,a2+1):
    lst.append(cal(i))
print(max(lst))

2017/12/17 13:35

얏홍

def cycle(num):
    count=1
    while num != 1:
        if num % 2 == 0:
            num = num / 2
            count += 1
        else:
            num = num * 3 + 1
            count += 1
    return count


def problem(a, b):
    max_count=0
    for i in range(a, b+1):
        if max_count < cycle(i):
            max_count = cycle(i)
    return max_count

def main():
    first=int(input(' enter first num :  '))
    second = int(input(' enter second num :  '))
    print(problem(first, second))

if __name__ == '__main__':
    main()

2017/12/19 17:22

윤병호

public class getCycleForOne {
    public int getCycle(int input) {
        int i = input;
        int cycle=1;
        while(i>1) {
            if(i%2==0) {
                i=i/2;
            }
            else{
                i=i*3+1;
            }
            cycle++;
        }
        return cycle;
    }

    public int biggestCycle(int a, int b) {
        int max=0;
        for(int i=a, tmp=0; i<=b; i++) {
            tmp=getCycle(i);
            if(tmp>max) {
                max=tmp;
            }
            else
                continue;
        }
        return max;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int m = s.nextInt();
        s.close();
        System.out.println(n + " " + m + " " +new getCycleForOne().biggestCycle(n, m));
    }
}

2017/12/26 15:01

김기덕

파이썬 3.6

def sequencelen(n):
    sequence = []
    sequence.append(n)
    while n != 1:
        if n % 2 == 0:
            n = n / 2
            sequence.append(int(n))
        else:
            n = n * 3 + 1
            sequence.append(int(n))
    return len(sequence)

def main(start,end):
    cycle = []
    for i in range(start,end+1):
        cycle.append(sequencelen(i))
    print("\n"" %d %d" %(start,end),max(cycle))

start = int(input(" ▶ 범위의 시작 숫자를 입력하세요: "))
end = int(input(" ▶ 범위의 끝 숫자를 입력하세요: "))

if __name__ == "__main__":
    main(start,end)
  • 결과값
 ▶ 범위의 시작 숫자를 입력하세요: 900
 ▶ 범위의 끝 숫자를 입력하세요: 1000

 900 1000 174

2018/01/02 23:11

justbegin

자바요

    public static void main(String[] args)
    {
        int cnt = -1;
        int tmpCnt = -1;
        main m = new main();
        System.out.println("두개의 정수를 입력하세요 ex) 1,1: ");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int num1 = Integer.valueOf(str.substring(0, str.lastIndexOf(',')));
        int num2 = Integer.valueOf(str.substring(str.lastIndexOf(',')+1,str.length()));
        for(int i = num1; i <= num2; i++)
        {
//          tmpCnt = m.cycle(i);
            tmpCnt = m.cycle_two(i);
            if(cnt != -1)
            {
                if(tmpCnt > cnt)
                    cnt = tmpCnt;
            }
            else
            {
                cnt = tmpCnt;
            }
            m.cnt_two = 1;
        }
        System.out.println(cnt);
    }

    //while문
    public int cycle(int num)
    {
        int res = num;
        int cnt = 1;

        while(res != 1)
        {
            cnt++;
            if(res %2 == 0)
            {
                res /= 2;
            }
            else
            {
                res = (res * 3) + 1;
            }
        }
        return cnt++;
    }

    //재귀
    int cnt_two = 1;

    public int cycle_two(int num)
    {
        if(num % 2 == 0)
        {
            cnt_two++;
            num /= 2;
            cycle_two(num);
        }
        else if(num != 1)
        {
            cnt_two++;
            num = (num * 3)+1;
            cycle_two(num);
        }
        return cnt_two;
    }

2018/01/09 13:34

강승규

x = int(input("수를 입력하세요"))
while x != 1:
       if x%2 == 0:
              x /= 2
              print(int(x))
              continue
       elif x%2 == 1:
              x = x*3+1
              print(int(x))
              continue

2018/01/09 19:23

김영성

import java.util.Arrays;
import java.util.Scanner;

public class Problem 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("두 정수를 입력하세요->");

        int start = input.nextInt();
        int end = input.nextInt();
        input.nextLine();//버퍼 날리기

        int[] store = new int[end-start+1];

        for(int i=0; i<store.length; ++i)
        {
            int count=0;
            int j = start;
            while(j != 1)
            {
                if(j%2==0)//짝수 라면
                {
                    j = j/2;
                    count++;
                }
                else if(j%2==1)//홀수 라면
                {
                    j = j*3+1;
                    count++;
                }
                if(j==1)
                    count++;
            }
            store[i] = count;
            start++;
        }

        int max = store[0];
        int index = 0;
        for(int i=1; i<store.length; ++i)
            if(max < store[i])
            {
                max = store[i];
                index = i;
            }

        System.out.println(Arrays.toString(store));
        System.out.println("최대 사이클의 인덱스는"+index);
        System.out.println("두 수의 모든수에 대하여 최대사이클의 수는"+max);
    }
}

2018/01/10 14:08

최태훈

파이썬으로 작성했습니다.

def cicle_max_length(num1, num2):
    mylist=[]
    for x in range(num1, num2+1):
        count=1
        while x>1:
            if x%2==0:
                count+=1
                x/=2
            else:
                count+=1
                x=x*3+1
        mylist.append(count)
    print(num1, num2, max(mylist))

cicle_max_length(1,100)
cicle_max_length(100,200)
cicle_max_length(201,210)
cicle_max_length(900,1000)

2018/01/16 17:12

박종범

g<-function(x,y){
  num<-1
  result <- NULL
  cnt<-NULL
  for(i in x:y){
    cnt[num]<-1
    result[num]<-i
    while(result[num]!=1){
      if(result[num]%%2 == 0){
        result[num]<-result[num]/2
      }
      else{
        result[num]<-result[num]*3+1
      }
      cnt[num]=cnt[num]+1
    }
    num=num+1
  }
  result <- c(x,y,max(cnt))
  print(result)
  print(cnt)
}

-----------------------------------------------

f <- function(i, j){
  max <- i   
  for(x in i:j) {
    cnt <- 1   
    repeat {
      cnt <- cnt+1
      if(x%%2==0) { x <- x/2  }
      else    { x <- x*3 + 1  }
      if(x==1) {break}
    }
    if(max < cnt+1) { max <- cnt+1 }
  }   
  print(max)
}

2018/01/17 12:10

Dong-il kim

def collatz_between(first, last):
    max_cycle = 0
    for i in range(first, last+1):
        cycle = 1
        while i != 1:
            if i%2 == 0:
                i = i / 2
                cycle += 1
            else:
                i = i*3 + 1
                cycle += 1
        if cycle > max_cycle:
            max_cycle, cycle = cycle, max_cycle
    return first, last, max_cycle

2018/01/17 19:33

Analyticsstory

r로 풀었습니다.

s1<-function(i, j){
  a<-NULL
  b<-rep(1,j-i+1)
  for(f in i:j){
    a[f-i+1]<-f
    while(a[f-i+1]!=1){
      if(a[f-i+1]%%2==0){a[f-i+1]<-a[f-i+1]/2}
      else{a[f-i+1]<-a[f-i+1]*3+1}
      b[f-i+1]<-b[f-i+1]+1
    }
  }
  return(paste(i,j,max(b)))
}

s1(900,1000)

2018/01/21 16:21

Seunghyuck Kim

function _process (x) {
  if ( x%2 == 0 ) {
    x =  x/2;
  } else {
    x = (x * 3 )+ 1;
  };
  return x;
};

function _record (x) {
  var _array = new Array;
  while (x >= 1) {
    if ( x == 1) {
      _array.push(x);
      break;
    } else {
    _array.push(x);
    x = _process(x); // _process(x)로 그냥 리턴을 x로 돌린다고 해서 x = _provess(x)와 동일하지 않다. 충격. 아마도 값만 출력하기 때문이 아닐까.
  };
  };
  return _array;
};



function _between (a, b) {
  var t = 0;
  for ( var i = a; i < b+1; i ++) {
    if ( _record(i).length > t) {
      t = _record(i).length;
    };
  };
return t;
};


console.log(_between(1,10))

2018/02/05 14:31

Yungbin Kim

# 파이썬


def problem_3n_1(n, m):
    m_cycle = 0
    for t in range(n, m+1):
        c_cycle = 0
        while 1:
            c_cycle += 1
            if t == 1:
                if m_cycle < c_cycle:
                    m_cycle = c_cycle
                break
            elif t % 2 == 0: t /= 2
            else: t = t*3 + 1
    return m_cycle


print(problem_3n_1(1, 10))
print(problem_3n_1(100, 200))
print(problem_3n_1(201, 210))
print(problem_3n_1(900, 1000))

2018/02/05 22:10

olclocr

def cyclen(n):
    if n%2 == 0:
        return cyclen(int(n/2))+1
    elif n == 1:
        return 1
    else:
        result = 1
        while n != 1:
            if n%2 == 0:
                n = int(n/2)
                result += 1
            else:
                n = 3*n+1
                result += 1
        return result

a = list()
n = input("범위를 입력하시오 (공백으로 구분):").split(' ')
for i in range(int(n[0]), int(n[1])+1):
    a.append(cyclen(i))
print(max(a))

2018/02/07 01:47

김동하

def threeone():
    ran=raw_input('range:')
    ran=ran.split(' ')
    ran=[int(x) for x in ran]
    r=range(ran[0],ran[1]+1)

    cycle=[]
    cyclelength=[]
    for i in r:
        n=i
        while not n==1:
            cycle.append(n)
            if n%2==0:
                n=n/2           
            else:
                n=(n*3)+1
        cycle.append(1)
        #print cycle
        cyclelength.append(len(cycle))
        cycle=[]
    print max(cyclelength)

2018/02/14 17:53

Da ne

def problem(n):
    counter=1
    while n!=1:
        if n%2==0:
            n=int(n/2)
            counter+=1
        elif n%2!=0:
            n=3*n+1
            counter+=1
    return counter


list_x=[]
list_y=[]
result_list=[]
line_num=int(input("숫자의 쌍 개수를 입력하세요\n"))

for k in range(line_num):
    list_x.append(int(input("왼쪽 숫자를 입력하세요\n")))
    list_y.append(int(input("오른쪽 숫자를 입력하세요\n")))



for g in range(line_num):
    nMax=-99
    for b in range(list_x[g],list_y[g]+1):
        if nMax<problem(b):
            nMax=problem(b)
    result_list.append(nMax)

for a in range(line_num):
    print("%d %d %d"%(list_x[a],list_y[a],result_list[a]))





2018/02/18 00:01

D B

#include <stdio.h>

int i, j;

int f(int);

int temp = 0;
int val = 0;

int main()
{
  scanf("%d %d", &i, &j);

  int k;  
  for (k = i; k <= j; k++)
  {
      temp = 0;
      f(k);
      if (val < temp) val = temp;
  }

  printf("\n%d %d %d", i, j, val);

  return 0;
}


int f(int n)
{
    temp++;

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

C로 작성했습니다.

2018/02/21 01:34

SiNam_

def cycle_length(n):
    cycle_list = [n]
    while n > 1:
        if n%2 == 0:
            n = int(n/2)  
        else:
            n = 3*n + 1
        cycle_list.append(n)
    return len(cycle_list)

def longest_cycle(i,j):
    length_list = []
    for x in range(i,j+1):
        length_list.append(cycle_length(x))
    return max(length_list)
print(longest_cycle(900,1000))

2018/02/23 17:41

맹재환

def SeqLen(n):
    if n==1: return 1
    elif n%2==0: Nextn = int(n/2)
    else: Nextn = 3*n+1
    return 1+SeqLen(Nextn)

def MaxLen(i,j):
    print(max(list(SeqLen(k) for k in range(i,j+1))))

2018/02/27 21:41

김자현

#include <stdio.h>

int LenSeq(n)
{
    if (n == 1) return 1;
    else if (n % 2 == 0) n = n/2;
    else n = 3 * n + 1;
    return 1 + LenSeq(n);
}
int main() 
{
    int FirVal, SecVal, i, re;
    re = 0;
    printf("자연수 2개를 작은것부터 입력해 주십시오.\n");
    scanf_s("%d", &FirVal); scanf_s("%d", &SecVal);
    for (i = FirVal; i < SecVal + 1; i++) {
        re = re > LenSeq(i) ? re : LenSeq(i);
    }
    printf("%d\n", re);
    return 0;
}

2018/02/27 21:58

탁성하

def count(n):
    count = 1
    while not n == 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
        count += 1
    return count

def cycle(i,j):
    list = []
    for x in range(i, j + 1):
        list.append(count(x))
    return(max(list))

i, j = map(int, input().split(' '))
print("%3d %3d %3d" %(i, j, cycle(i,j)), end = ' ')

깔끔하게 코드를 줄여보도록 개선할 예정입니다.

2018/03/13 22:56

yonggyu park

(i,j)=(int(input('i:')),int(input('j:')))
M=[]
for x in range(i,j+1):
    a=[x]
    while x != 1:
        if x%2 == 0:
            x=x/2
        else:
            x=3*x+1
        a.append(int(x))
    M.append(len(a))
print((i,j,max(M)))

2018/03/18 04:35

python

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Problem {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        int[] i = new int[4];
        int[] j = new int[4];

        for(int n = 0; n <4; n++){
            i[n] = sc.nextInt();
            j[n] = sc.nextInt();
        }

        for(int l = 0; l < 4; l++){
            int cycleMaxmum = 0;
            for(int k = i[l]; k<=j[l]; k++){
                List<Integer> list = new ArrayList<>();
                int m = k;
                list.add(m);
                while(m != 1){
                    if(m % 2 == 1){ //홀수 일때
                        m = 3*m +1;
                    }else{ //짝수일때
                        m /= 2;
                    }
                    list.add(m);
                }
                if(cycleMaxmum < list.size()){
                    cycleMaxmum = list.size();
                }
            }
            System.out.println(cycleMaxmum);
        }

    }

}

2018/03/20 15:15

김태훈

#include <stdio.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int three_n_plus_one(int n){
    int clen = 1; // cycle-lenth

    while(n > 1){
        if(n % 2 == 0)
            n /= 2;
        else
            n = 3*n + 1;
        clen++;
    }
    return clen;
}

int main(int argc, char** argv) {

    int n;
    int s_num, e_num;
    printf("두 숫자 i, j 입력 (ex : 1 10) : ");
    scanf("%d %d", &s_num, &e_num);

    printf("%d %d", s_num, e_num);
    int top_clen, tmp = 0;
    for(;s_num <= e_num; s_num++){
        if((tmp = three_n_plus_one(s_num)) > top_clen)
            top_clen = tmp;
    }

    printf(" %d", top_clen);

    return 0;
}

2018/03/21 02:41

pope john

def cycle(a):
    suyeol = [a]
    while True:
        if suyeol[-1] % 2 == 0:
            suyeol.append(suyeol[-1]//2)
        elif suyeol[-1] % 2 !=0 and suyeol[-1] != 1:
            suyeol.append(3 * suyeol[-1] + 1)
        else :
            break
    return len(suyeol)

def max_cycle_len(a,b):
    len = 0
    for i in range(a,b+1):
        if cycle(i) >= len :
            len = cycle(i)
    print(a,b,len)
max_cycle_len(1,10)
max_cycle_len(100,200)
max_cycle_len(201,210)
max_cycle_len(900,1000)

2018/03/27 00:36

최의현

// 3n+1 Problem
package main

import (
    "fmt"
)

func main() {
    var start, end int
    fmt.Scanf("%d %d", &start, &end)
    var maxCycle int
    for i := start; i <= end; i++ {
        if val := cycleLen(i); val > maxCycle {
            maxCycle = val
        }
    }
    fmt.Println(maxCycle)
}

func cycleLen(n int) int {
    rst := []int{n}
    seq := n
    for seq != 1 {
        if seq%2 == 0 {
            seq /= 2
        } else {
            seq = 3*seq + 1
        }
        rst = append(rst, seq)
    }
    return len(rst)
}

2018/03/27 18:13

mohenjo

a, b = input().split()
alist = []
blist = []
for i in range(int(a), int(b) + 1):
    count = 1 
    while True:
        if i == 1:
            break
        elif i % 2 == 0:
            i = i / 2
            count = count + 1
        elif i % 2 == 1:
            i = 3 * i + 1
            count = count + 1
    alist.append(count)
alist.sort()
print(alist[len(alist)-1])

2018/03/31 19:51

최성범

def prob(i,j) :
    result = []
    for n in range(i,j+1):
        cycle = 1
        while n != 1:
            if n % 2 ==0 : n = n/2
            else : n = 3 * n + 1
            cycle += 1
        result.append(cycle)
    return max(result)

print(prob(1,10))
print(prob(100,200))
print(prob(201,210))
print(prob(900,1000))

2018/04/01 17:39

yijeong

def mcycle():
    i,j =map(int, input('숫자 2개를 입력하세요. : ').split())
    length=[]
    for x in range(i,j+1):
        tracking=[]
        while x != 1:
            tracking.append(x)
            if x%2==0:
                x=x/2
            elif x%2==1:
                x=3*x+1
        length.append(len(tracking+[1]))
    return print(i,j,max(length),sep='  ')

2018/04/07 18:11

thuruk

#해당 연산을 실행하는 함수
def calculrator(a) :
    if a % 2 == 0 :
        result = a/2
        return result
    else :
        result = 3*a+1
        return result
#사이클 길이를 알아내는 함수
def cycle_length(a) :
    i=1
    while 1 :
        if a == 1 : break
        else :
            i=i+1
            a = calculrator(a)
    return i
x = int(input("첫번째 수를 입력하세요(정수) : "))
y = int(input("두번째 수를 입력하세요(정수) : "))
#리스트를 만들어서 각각의 사이클 길이를 추가했어요, 
#그리고 마지막으로 리스트를 정렬해서 가장 높은 사이클 길이 출력했습니다.
cycle_leng = []
for i in range(x,y+1) :
    cycle_leng.append(cycle_length(i))
cycle_leng.sort()
print(cycle_leng[-1])
#파이썬 초보라 기초적인 문법으로만 작성했어요 ㅜㅜ 태클환영입니당

2018/04/08 19:20

이재빈

Swift입니다.

import Foundation

func getCycleLength(_ givenNumber: Int) -> Int {
    var number = givenNumber
    var count = 1
    while number != 1 {
        number = number % 2 == 0 ? number / 2 : number * 3 + 1
        count += 1
    }
    return count
}

func getMaxCycleLength(_ from: Int, _ to: Int) -> Int {
    var max = 0
    for i in from...to {
        let cycleLength = getCycleLength(i)
        if cycleLength > max {
            max = cycleLength
        }
    }
    return max
}

print( getMaxCycleLength(  1,   10) ) //  20
print( getMaxCycleLength(100,  200) ) // 125
print( getMaxCycleLength(201,  210) ) //  89
print( getMaxCycleLength(900, 1000) ) // 174

2018/04/12 02:21

졸린하마

파이썬 3 입니다

def n_x_3_plus_1(x, y):
    def n_x_3list(t):
        result = [t]
        while t > 1:
            if t % 2 == 0:
                t *= 0.5
                result.append(t)
            else:
                t *= 3
                t += 1
                result.append(t)
        return result
    result_ = max(len(n_x_3list(i)) for i in range(x, y+1))
    return result_

2018/04/12 11:30

charming

a = int(input("Enter the start point: ", ))
b = int(input("Enter the end point: ", ))

list=[]
cycle_len=[]

def max_len_of_cycle(x, y):
    for i in range(x, y+1):
        cycle_len.append(cycle(i))
    print(cycle_len)
    return print(max(cycle_len), i)



def cycle(a):
    if a%2==0:
        list.append(a)
        a=int(a/2)
        return cycle(a)
    else:
        if a == 1:
            list.append(a)
            l = len(list)
            list.clear()
            return l
        else:
            list.append(a)
            a=3*a+1
            return cycle(a)

max_len_of_cycle(a, b)

2018/04/13 21:35

KangSan Jeon

public class hello {
    public static void main(String[] args){
        Scanner sc = new Scanner(System. in);
        System.out.println("숫자를 입력하세요:");
        int a = sc.nextInt();

        while(a>=1){
            if(a==1)
                break;
            if(a%2 == 0){
                a = a/2;
                System.out.print(a+" " );
            }
            else{
                a = a*3+1;
                System.out.print(a+" " );
            }
        }

        }
    }

2018/04/16 12:34

聂金鹏

def cycle(i, j):
    count = 0
    for a in range(i, j + 1):
        times = 1
        make = a
        while make != 1:
            times += 1
            if make % 2 == 1: make = make * 3 + 1
            else: make /= 2
        if times > count: count = times
    return count
print(cycle(201, 210))
# 결과: 89

Python 3

2018/04/28 12:09

myyh2357

package codingDojang;

import java.util.ArrayList;
import java.util.Scanner;

public class Test23 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int input1 = 0;
        int input2 = 0; 
        int temp = 0;

        ArrayList<Integer> arr1 = new ArrayList<Integer>();
        ArrayList<Integer> arr2 = new ArrayList<Integer>();

        Scanner scan1 = new Scanner(System.in);
        Scanner scan2 = new Scanner(System.in);

        System.out.println("시작 정수를 입력하세요.");
        int scanInput1 = scan1.nextInt();
        System.out.println("종료 정수를 입력하세요.");
        int scanInput2 = scan2.nextInt();

        input1 = scanInput1;
        input2 = scanInput2;

        arr1.add(input1);
        arr2.add(input2);


        for ( int i = input1 ; i <= input2 ; i++) {

            input1 = i ;
            arr1.clear();
            arr1.add(input1);
            while (input1 != 1) {

                if (input1 % 2 == 0) {
                    input1 = input1 / 2;
                } else {
                    input1 = input1 * 3 + 1;
                }
                arr1.add(input1);
            }

            if (arr1.size() > temp) {
                temp = arr1.size();
            }
        }

        System.out.println(scanInput1 + "  "+ scanInput2 + "  "+temp);
    }
}

2018/05/01 12:50

이지환

// 자바입니다
 public static void main(String[] args) throws Exception { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int m = Integer.parseInt(str[0]);
        int n = Integer.parseInt(str[1]);
        int ans = 0;
        for (int j=m; j<=n; j++) {
            int cnt = 1;
            int d = j;
            while(d != 1) {       
              d = (d%2==0) ? d/2 : d*3+1;
              cnt++;
            } 
            ans = Math.max(ans, cnt);
        }
        System.out.println(ans);
    }

2018/05/05 11:46

정몽준

def math(n): # n at integer result = [] result.append(n) while True: if n % 2 == 0: n = n / 2 result.append(int(n)) if n == 1: break elif n % 2 == 1: n = n * 3 + 1 result.append(int(n)) if n == 1: break return len(result)

i1 = input("Enter two numbers: ") i2 = i1.split() start = int(i2[0]) finish = int(i2[1]) final_list = []

for number in range(start,finish): a = math(number) final_list.append(a)

final_list.sort() ff = final_list[-1]

print("{} {} {}".format(start,finish,ff))

2018/05/05 21:10

최우성

맵을 사용해서 값을 저장해두면 이미 계산한 결과가 있을 때 계속 값을 보낼 필요가 없다

 def toOne(a:Int, b:Int):Int = {
      import scala.collection.mutable.Map
      val hash = Map[Int, Int]()

      def count(n: Int, cnt: Int):Int = {
        n match {
          case 1 => cnt
          case x if hash.get(n) != None => cnt + hash(n) - 1
          case x if x % 2 == 1 => count(3*n + 1, cnt + 1)
          case x if x % 2 == 0 => count(x/2 , cnt + 1)
        }
      }

      var maxCnt = 0
      (a to b).foreach{
        v =>
          {
            hash(v) = count(v, 1)
            maxCnt = Math.max(maxCnt, hash(v))
          }
      }
      maxCnt
    }
    toOne(500 ,1000)

2018/05/19 10:11

한강희

python3

def calculate(num):
    cnt = 1
    while num!= 1:
        if num%2 == 0:
            num /= 2
            cnt+=1
        else:
            num = num*3+1
            cnt+=1
    return cnt

inp = input()
inp1, inp2 = inp.split()
res = []

for i in range(int(inp1), int(inp2)+1):
    res.append(calculate(i))


res.sort(reverse=True)
print(res[0])

2018/05/29 16:14

bnewkk

Python 3.6.4

def numcount(n):
  i = 1
  while n! = 1:
    if n % 2 == 0:
      n = n//2
      i += 1
    else:
      n = 3*n+1
      i += 1
    return i

def totalnumcount(i, j):
  numlist = []
  for n in range(i ,j+1):
    numlist.append(numcount(n))
  print("%d %d %d" % (i, j, max(numlist))

-----------------------------------------------
totalnumcount(1, 10)
totalnumcount(100, 200)
totalnumcount(201, 210)
totalnumcount(900, 1000)

output:
1 10 20
100 200 125
210 210 89
900 1000 174

2018/06/01 21:05

Gerrad kim

Python

test = [[1,10], [100, 200], [201, 210], [900, 1000]]

for t in test:
    i, j = t
    ans = 0
    for x in range(i, j+1):
        lst = list()
        while True:
            if x != 1:
                lst.append(x)
                if x%2 == 0:
                    x /= 2
                else:
                    x = 3*x + 1
            else:
                lst.append(x)
                break
        ans = max(ans, len(lst))
    print(ans)

2018/06/04 15:37

Taesoo Kim

def threenone(x,y):
    l=[]
    for i in range (x,y+1):
        k=[i]
        while i !=1:
            if i%2 == 0: 
                i = i/2        
            else:
                i = i*3+1
            k.append(i)
        l.append(len(k))
    return max(l)

2018/06/07 01:31

Kwak, Chuljung

def exam(n):
    n = [n]
    while(n[-1]!=1):
        if n[-1] % 2 == 0: n.append(n[-1]//2)
        else: n.append(n[-1] * 3 + 1)
    return len(n)

i, j = map(int,input("i j? (공백을 사용하여 두 숫자를 입력): ").split())
print(max([exam(n) for n in range(i,j)]))

# Output:
#1    10    20
#100  200   125
#201  210   89
#900  1000  174

2018/06/24 00:25

재즐보프

#include<stdio.h>

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

int cycle_num(int n)
{
    int i = 0;
    while (n != 1)
    {
        n = cycle(n);
        i++;
    }
    return i;
}

int main()
{
    int i, j,n; 
    scanf_s("%d %d", &i, &j);
    int m = cycle_num(i);
    for (n = i; n <= j; n++)
    {
        if(cycle_num(n)>m)
            m=cycle_num(n);
    }
    printf("%d\n", m);
}

2018/07/02 12:56

이종희

파이썬

def next(n):
    if n == 1:
        return -1
    elif n % 2 == 0:
        return n / 2
    else:
        return n * 3 + 1

def cycle(n):
    count = 0
    temp = n
    while temp:
        if next(temp) > 0:
            temp = next(temp)
            count += 1
        else:
            return count + 1 #1을 포함하는 횟수

def max_cycle(i, j):
    max = 0
    for x in range(i, j+1):
        if cycle(x) > max:
            max = cycle(x)
    return max

print(max_cycle(900, 1000)) #ans: 174

2018/07/06 08:40

WJ K

메모이제이션

cicle = {1:1,2:2}
def ciclelen(n):
    if n not in cicle:
        if n%2 == 0:
            cicle[n] = 1+ciclelen(n/2)
        else:
            cicle[n] = 1+ciclelen(3*n+1)
    return cicle[n]

if __name__=='__main__':
    inv = []
    while 1:
        inv.append(tuple(map(int,input().split())))
        if inv[-1] == (): del inv[-1];break
    for a,b in inv:
        print('{:5} {:5} {:5}'.format(a,b,max(ciclelen(i) for i in range(a,b+1))))

일반재귀

def ciclelen(n):
    if n == 1: return 1
    if n == 2: return 2
    if n%2 == 0:
        return 1+ciclelen(n/2)
    else:
        return 1+ciclelen(3*n+1)

결과

1 10
100 200
201 210
900 1000

    1    10    20
  100   200   125
  201   210    89
  900  1000   174

2018/07/08 11:03

Creator

// 3n+1 Problem package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(true)
    {
        System.out.print("두 수 입력: ");
        int i = sc.nextInt();
        int j = sc.nextInt();
        if(i == 0 || j == 0)
            break;
        printMax(i, j);
    }
}

public static int getCycleLen(int num)
{
    int count = 0;
    while(true)
    {
        if (num == 1)
        {
            count++;
            break;
        }
        else if (num % 2 == 0)
        {
            count++;
            num = num / 2;
        }
        else
        {
            count++;
            num = num * 3 + 1;
        }
    }
    return count;
}

public static void printMax(int i, int j)
{
    int max = 0;
    int maxnum = 0;
    if(i > j)
    {
        int temp;
        temp = j;
        j = i;
        i = temp;
    }
    for(int k = i; k <= j; k++)
    {
        if(getCycleLen(k) > max)
        {
            maxnum = k;
            max = getCycleLen(k);
        }
    }
    System.out.println("최대: " + maxnum + "의 싸이클길이 = " + max);
}

}

2018/07/13 19:40

이동수

    class Program
    {
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(' ');

            int nCnt = 0;
            int nFst = int.Parse(input[0]);
            int nSec = int.Parse(input[1]);
            int nMax = 0;

            for (int i = nFst; i < nSec; i++)
            {
                for (int j = i; j != 1; )
                {
                    nCnt++;
                    if (j % 2 == 0)
                    {
                        j = j / 2;
                    }
                    else
                    {
                        j = (j * 3) + 1;
                    }
                }
                Console.WriteLine(i + " 의 길이 : " + nCnt);

                if (nCnt > nMax)
                    nMax = nCnt;

                nCnt = 1;
            }
            Console.WriteLine("최대 사이클 길이 :" + nMax);
        }
    }

2018/07/25 00:21

정태식

#3n+1 Problem


def counting(user_get):
    count=0
    while user_get != 1:         #user_get =1 일경우는 어떻게 처리해야하나.

        if user_get%2 == 1:
            user_get = user_get*3 +1
            count+=1

        elif user_get %2 == 0 :
            user_get=user_get/2
            count+=1


    return count


def finding( x, y):
    moum=set()
    for i in range(x,y+1):
        moum.add(counting(i))

    a=max(moum)
    return a




x=int(input('첫번째 수를 입력하세요'))
y=int(input('두번째 수를 입력하세요'))

print(finding(x,y))

파이썬으로 풀어봤습니다....

2018/07/26 14:10

IN K

def maximum_cycle(n, count):
    if n==1: 
        count+=1
        return count
    elif n%2==0:
        count+=1
        return maximum_cycle(n/2, count)
    else:
        count+=1
        return maximum_cycle(3*n+1, count)

first, second = input().split()
first = int(first); second = int(second)
maximum = 0

for i in range(first,second+1):
    temp = maximum_cycle(i,0)
    if(temp > maximum): maximum = temp

print(maximum)

2018/07/30 14:09

박용주

c언어
#include <stdio.h>


int main()
{
    int num,num1,num2;

    int i;
    int count =1;
    int a_c = 0;
    int max;
    int len;


    do
    {
        printf("두개의 정수 i와 j를 입력하세요 : j가 i보다합니다.(j>i) ");
        scanf("%d %d", &num1, &num2);

    }while(num2<num1);

    len = (num2 - num1)+1;

    int c_arr[len] ={0, };

    for(i=num1; i<=num2; i++)
    {
        num = i;

        do
        {       
            if(num%2==0)
            {
                num = num/2;
            }else
            {
                num = (3*num)+1;
            }
            c_arr[a_c]++;

        }while(num!=1);

        a_c++;
    }

    max = c_arr[0];

    for(i=0; i<len; i++)
    {
        if(max < c_arr[i])
        {
            max = c_arr[i];
        }
    }
    printf("%d", max+1);
}

2018/08/12 23:06

이우경

Max cycle인 인수도 표시해 보았습니다.

def cy(a,b):
    d = dict()
    for n in range(a, b + 1):
        c = 1
        b = int(n)
        while b != 1:
            if b % 2 == 0:
                b = b / 2
                c += 1
            else:
                b = b * 3 + 1
                c += 1
        d[c] = n
    return max(d.keys()), d[max(d.keys())]

2018/08/18 07:31

김건우


def func(n):
    f=True
    D=[n]
    while f:
        if n%2==0:#짝수
            n=n//2
            D.append(n)
        elif n%2==1:#홀수
            n=(n*3)+1
            D.append(n)
        if n==1:
            f=False
    return len(D)

result =[]
i=int(input("최소값:"))
j=int(input("최대값:"))
for x in range(i,j+1):
    result.append(func(x))
print(max(result))

2018/08/18 13:42

S.H

package test;

public class test {
    public static void main(String[] args) {
        int[][] num = { { 1, 10 }, { 100, 200 }, { 201, 210 }, { 900, 1000 } };
        for (int j = 0; j < num.length; j++) {
            int n = 0;
            for (int i = num[j][0]; i <= num[j][1]; i++) {
                int temp = cycle(i);
                n = temp > n ? temp : n;
            }
            System.out.println(num[j][0] + "\t" + num[j][1] + "\t" + n);
        }
    }

    private static int cycle(int n) {
        int count = 2;
        while ((n = n % 2 == 0 ? n / 2 : n * 3 + 1) != 1)
            count++;
        return count;
    }
}

2018/08/25 22:44

김지훈

def collatz(n, cyc):  # cyc엔 1을 받자.
    while n > 1:
        if n%2 == 0:
            n = n/2
            cyc += 1
            return collatz(n, cyc)
        else:
            n = 3*n + 1
            cyc += 1
            return collatz(n, cyc)
    else:
        return cyc

i = int(input("put number"))
j = int(input("put number"))

longest = 0
for k in range(i, j+1):  # collatz()를 수행하여 최댓값만을 저장하고 싶다. 
    d = collatz(k, 1)
    longest = max(longest, d)

print(longest)

저는 python을 사용하였습니다. 재귀함수에 대해서 공부할 수 있는 좋은 예제였네요~ 아직은 미숙합니다ㅜㅜ

2018/08/28 22:15

aa

C#

using System;

namespace CD023
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Input range (min max): ");
            string[] input = Console.ReadLine().Split();
            int min = int.Parse(input[0]);
            int max = int.Parse(input[1]);
            int result = GetMaxCycleLen(min, max);
            Console.WriteLine($"{min} {max} {result}");
        }

        static int GetCycleLen(int aNumber) // 수열 길이 반환
        {
            int count = 1;
            while (aNumber != 1)
            {
                if (aNumber % 2 == 0) { aNumber /= 2; }
                else { aNumber = 3 * aNumber + 1; }
                count++;
            }
            return count;
        }

        static int GetMaxCycleLen(int beginNumber, int endNumber) // 범위 내 최대 수열 길이 반환
        {
            int maxLen = 0;
            for (int i = beginNumber; i <= endNumber; i++)
            {
                int tmp = GetCycleLen(i);
                maxLen = tmp > maxLen ? tmp : maxLen;
            }
            return maxLen;
        }
    }
}

2018/08/29 15:35

mohenjo

Scanner sc = new Scanner(System.in);

        System.out.print("첫 번째 숫자 : ");
        int num1 = sc.nextInt();

        System.out.print("두 번째 숫자 : ");
        int num2 = sc.nextInt();

        int temp = cycle(num1);
        for (int i = num1; i < num2 + 1; i++) {
            if (cycle(i + 1) > temp) {
                temp = cycle(i + 1);
            }
        }
        System.out.print("결과 값 : "  + temp);
        sc.close();
    }

    private static int cycle(int num) {
        int count = 1;

        while (true) {
            if (num % 2 == 0) {
                num = num / 2;
            } else {
                num = num * 3 + 1;
            }
            count++;
            if (num == 1) {
                break;
            }
        }
        return count;
    }

2018/09/01 17:02

채규빈

가장 원초적이고 단순하게 풀어봤습니다!


l= []
for i in range(900,1000+1):   #  900, 1000 대입
    lst = [i]    
    while i != 1:
        if i%2 == 0:
            i = i/2
        else:
            i = i*3+1
        lst.append(i)    
    l.append(len(lst))
max(l)

2018/09/03 21:31

김동률

# 3n+1 Problem

str1 = input()
str1 = str1.split(" ")

nums = [int(x) for x in str1]
count_list = []

for i in range(nums[0],(nums[1]+1)):
    count = 1
    while i != 1:
        i=i/2 if i%2==0 else i*3+1
        count += 1
    count_list.append(count)

maxNum = max(count_list)

print("%s %s %s"% (nums[0],nums[1],maxNum))

2018/09/04 22:18

오왕씨

def f(n):

    l = [n]

    while n != 1:

        if n%2 ==0:
            n= n//2
            l.append(n)
        elif n%2 == 1:
            n= n*3 +1
            l.append(n)
    return len(l)

# n = int(input())
# print(f(n))

fl = []

a, b = map(int,input().split())
for i in range(a,b):
    fl.append(f(i))

print(max(fl))

900 1000

174

2018/09/28 14:44

Charlie Jeong

x, y = map(int,input().split())
Max_cycle = 0
cycle = 0

for i in range(x,y+1):
    cycle = 0
    j = i
    while j > 1:
        if j%2 == 0:
            j = j//2
            cycle = cycle + 1
        else:
            j = j * 3 + 1
            cycle = cycle + 1   
    cycle = cycle + 1    

    print(i,cycle)

    if Max_cycle < cycle:
        Max_cycle = cycle

print(x,y,Max_cycle)

2018/10/23 14:42

Dae Su Jeong

def input_num() :
    num_list = []
    while 1 :
        num= input()
        if(num=="x") :
            break
        else :
            #입력받은 숫자를 리스트에 넣는다
            num_list.append(num)
            continue

    return num_list

def max_cnt(i, j) :
    max_cnt = 0
    for a in range (i, j+1) :
        num = a
        num_cnt = 0
        while 1 :
            num_cnt+=1
            if num==1 :
                if num_cnt >= max_cnt :
                    max_cnt = num_cnt
                break
            elif num%2 == 0 :
                num /= 2
                continue
            elif num%2 != 0 :
                num *= 3
                num += 1
                continue
    return max_cnt


def problem() :
    num_list = input_num()
    for i in range (0, len(num_list)-1,2) :
        cnt = max_cnt(int(num_list[i]), int(num_list[i+1]))
        print (num_list[i] + "\t" + num_list[i+1] + "\t" + str(cnt))

2018/11/05 22:52

쨔이

def cycle(n):
    null=[n]
    while n!=1:
        if n%2 == 0:
            n = n/2
            null.append(n)
        else:
            n = 3*n+1
            null.append(n)
    return len(null)
answer =[]
i= int(input("상한입력:"))
j= int(input("하한입력:"))
for k in range(i,j+1):
    answer.append(cycle(k))

print(max(answer))

2018/11/12 14:50

배득주

def cycle(n):
    num = n
    cyclelen = 1
    while num != 1:
        if num % 2 == 0:
            num /= 2
            cyclelen += 1
        else:
            num = num*3 + 1
            cyclelen += 1
    return cyclelen

i = int(input())
j = int(input())
if i > j:
    i, j = j, i

candi = [cycle(x) for x in range(i, j+1)]
print(max(candi))


2018/11/19 00:57

그사람 남한 볼 수 있어요

c언어

#include <stdio.h>
int main()
{
    int i , j;
    int len=1, n=0, x=0, size=0; 
    //len은 사이클길이, n은 i에서 j까지의 수를 위한 변수

    scanf("%d %d", &i, &j);


    for(x=i;x<=j;x++){
        n=x;
        while(n!=1){
            if(n%2==0)n/=2;
            else n=3*n+1;
            len++;
        }
        if(size<len)size=len;
        len=1;
    }

    printf("최대 사이클 길이:%d", size);
    return 0;
}

2018/11/21 23:19

이호석

import java.util.Scanner;

public class KimSanghyeop
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("시작 값 입력 : ");
        int num1 = sc.nextInt();

        System.out.print("마지막 값 입력 : ");
        int num2 = sc.nextInt();

        int f1,f2,f3,cnt,temp;
        int max =0;


        for(f1=num1;f1<=num2;f1++)
        {
            cnt=1;
            temp=f1;
            while(temp!=1)
            {
                if(temp %2 ==0)
                {
                    temp = temp /2;
                }   
                else
                {
                    temp = temp*3 + 1;  
                }

                cnt++;
            }

            if(cnt > max)
            {
                max=cnt;
            }

        }

        System.out.println("가장 큰 길이 : "+max);

    }
}

2018/12/06 13:55

김상협

def func(nof):
    if nof%2==0:
        return nof/2
    elif nof%2==1:
        return (nof*3)+1


def main():
    num1 = int(input('시작수'))
    num2 = int(input('끝수'))
    box=[]
    for i in range(num1,num2+1):
        cnt = 0
        while i != 1:
            cnt += 1
            i = func(i)
        box.append(cnt)
    print(max(box))

main()

2018/12/10 18:21

현모구

tmp = 1
x, y = map(int, input("두 자연수 입력 : ").split())
for i in range(x, y+1) :
    trial = 1
    while i != 1 :
        if i % 2 == 0 :
            i = i / 2
        else :
            i = (3*i) + 1
        trial += 1
    if trial > tmp :
        tmp = trial
print(tmp)

2019/01/04 19:25

lucky1to10

def cal(nume):
    num = nume
    cycle = [] + [num]
    while True:
        if num == 1:
            break
        elif num % 2 == 0:
            num = num // 2
            cycle += [num]
        else:
            num = 3 * num + 1
            cycle += [num]
        if cycle[-1] == 1:
            break
    return len(cycle)

def cal_max(start, end):
    len_list = []
    for num in range(start, end+1):
        len_list += [cal(num)]
    print(start, end, max(len_list))

cal_max(900, 1000)

출력 : 900 1000 174

2019/01/11 11:21

판다네밥상

#include<algorithm>
#include<iostream>
#include<vector>

using namespace std;

void algol(int num,vector<int>&);



int main(void)
{
    vector<int>cv; vector<int>::iterator itr;
    int small;
    cout << "최소의수>>";
    int big;
    cin >> small;
    cin.ignore();
    cout << "최대의수";
    cin >> big;
    int i;
    for ( i = small; i <= big; i++)
    {
        algol(i,cv);
    }
    sort(cv.begin(), cv.end());
    cout << cv[cv.size() - 1];

}
void algol(int num,vector<int>&cv)
{
    int cnt = 0;
    while (1)
    {
        if (num == 1) {
            cnt++; break;
        }if (num % 2 == 0)
        {
            num = num / 2; cnt++;

        }
        else
        {

            num = 3 * num + 1; cnt++;
        }

    }
    cv.push_back(cnt);
}

2019/01/21 15:03

김상범

n1, n2 = map(int,input().split())
total = []
for i in range(n1, n2 + 1):
    cnt = 1
    while True:
        if i == 1:
            break
        elif i % 2 == 0:
            i = i / 2
        else:
            i = 3 * i + 1
        cnt += 1
    total.append(cnt)
total.sort(reverse = True)
print(total[0])

2019/01/25 12:17

D.H.

def calc_perm_cycle(n):
    cycle = 1
    while n > 1:
        n = n // 2 if 0 == n%2 else n*3 + 1
        cycle += 1
    return cycle

def get_max_cycle(start, end):
    max_cycle = 0
    for i in range(start, end + 1):
        cycle = calc_perm_cycle(i)
        if cycle > max_cycle:
            max_cycle = cycle
    return max_cycle

test_set = [[1, 10], [100, 200], [201, 210], [900, 1000]]
for test in test_set:
    max_cycle = get_max_cycle(test[0], test[1])
    print('{:<4d} {:<4d} {:<4d}'.format(test[0], test[1], max_cycle))

2019/01/27 17:50

Roy

#include <stdio.h>

int main(void)
{
    int i, j, n, k, cnt, max = 0;
    scanf("%d%d", &i, &j);
    for (k = i; k <= j; k++)
    {
        n = k;
        cnt = 1;
        while (n!=1)
        {
            if (n % 2 == 0)
            {
                n /= 2;
            }
            else
            {
                n = 3 * n + 1;
            }
            cnt++;
        }
        if (max < cnt) max = cnt;
    }
    printf("%d", max);
    return 0;
}

음.. 레벨 1에 더 가까운 거 같네요

2019/01/31 22:26

김태헌

def MaxCycle(start,end):
    max=0
    for i in range(start,end+1):
        count=1
        while i!=1:
            if i%2==0: i//=2
            else: i = 3*i+1
            count+=1

        if max < count: max = count
    return max
print(MaxCycle(201,210))

2019/02/09 21:03

얀차

#n이라느 정수를 입력받고 짝수면 2로 나누고 홀수면 3을 곱한뒤 1을 더해서 1이 될때까지 프린트 하시오

def oddeven(i,j):
    n=range(i,j+1)
    result=[]

    for i in n:
        length = 0
        while(1):
            if i==1:
                length+=1
                result.append(length)
                break
            elif i%2==0:
                length+=1
                i=i/2
            else:
                i=3*i+1
                length+=1
    Max=result[0]
    for a in result[1:]:
        if Max<a:
            Max=a
    return Max

print(oddeven(100,200))

2019/02/13 23:25

성진우

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            InputLength(1, 10);
            InputLength(100, 200);
            InputLength(201, 210);
            InputLength(900, 1000);
        }
        static int FindCycle(int n)
        {
            int cycle = 0;
            while (n != 1)
            {
                if (n % 2 == 0)
                {
                    cycle++;
                    n /= 2;
                }
                else
                {
                    cycle++;
                    n = n * 3 + 1;
                }
            }
            return cycle;
        }
        static void InputLength (int a, int b)
        {
            int max_cycle = 0;
            for (int i = a; i <= b; i++)
            {
                int result = FindCycle(i);
                if (result > max_cycle)
                {
                    max_cycle = result;
                }
            }
            Console.WriteLine(max_cycle + 1);
        }
    }
}

2019/02/15 12:33

bat

i,j = map(int,input("i,j 입력 (공백 구분): ").split(' ')) #input받은 문자열을 split 한 후 int함수를 거쳐 i,j에 들어가는 것
cycle = 1
cycle_list=[]

for n in range (i,j+1):
    while n!=1:
        if n%2==0:
            n=n/2
        else:
            n=n*3+1
        cycle+=1
    cycle_list.append(cycle)
    cycle=1

print(max(cycle_list))

2019/02/18 09:09

var input = '100 200';
var arr = input.split(' ');
var a = parseInt(arr[0]);
var b = parseInt(arr[1]);

var tmp = b;
var maxCount = 0;

for (var i = a; i <= b; i++) {
    var tmp = i;
    var count = 1;
    while (tmp > 1) {
        if (tmp % 2 == 0) { //짝수
            tmp = tmp / 2
        } else {           // 홀수
            tmp = tmp * 3 + 1;
        }
        count++;
    }
    maxCount = Math.max(count, maxCount);
}
console.log(maxCount);

2019/02/18 19:29

이계민

def s():
    list1=[]
    for x in range(int(input()),int(input())+1):
        n=1
        while x!=1:
            if x%2==1:
                x=x*3+1
                n+=1
            elif x%2==0:
                x=x/2
                n+=1
        listx=[n]
        list1.append(listx)
    print(max(list1))            
s()

2019/02/19 20:15

소요자재

final = []
try :
    while(True) :
        cycleMax = 0
        i1 = int(input("첫번째 숫자 : "))
        i2 = int(input("두번째 숫자 : "))
        for i in range(i1, i2 + 1) :
            result = []
            result.append(i)
            while result[-1] != 1 :
                if result[-1] % 2 == 0 :
                    result.append(int(result[-1] / 2))
                else :
                    result.append(result[-1] * 3 + 1)
            if len(result) > cycleMax :
                cycleMax = len(result)
        #print(i1, i2, cycleMax)
        final += i1, i2, cycleMax, "\n"
except :
    for i in final :
        print(i, end=' ')

2019/02/21 23:31

좋은나쎔

def cycle(d):
    count = 0
    while d != 1:
        if d % 2 == 0:
            d = d / 2
        else:
            d = 3*d + 1
        count += 1
    return count+1


start, end = input().split()
max_len = 0
for x in range(int(start), int(end)+1):
    if max_len < cycle(x):
        max_len = cycle(x)

print(max_len)

2019/02/23 03:22

농창

num1 = int(input('첫번째 숫자 입력'))
num2 = int(input('두번째 숫자 입력'))
a = []
for i in range(num1, num2 + 1):
    a.append(i)
c = []
for i in range(num1, num2 + 1):
    b = []
    while i != 1:
        if i % 2 == 0:
            i = i // 2
        else:
            i = i * 3 + 1
        b.append(i)
    c.append(len(b))
if max(c):
    d = c.index(max(c))
print(a[d])

2019/02/27 15:40

끽끼끽끼

def collatzstep(n):
    step=0
    while n!=1:
        if n%2==1:
            n=3*n+1
        else:
            n=n//2
        step+=1
    return step

maxstep=0
a=int(input("Starting number: "))
b=int(input("Ending number: "))

for i in range(a,b+1):
    if collatzstep(i)>maxstep:
        maxstep=collatzstep(i)

maxcycle=maxstep+1
print(maxcycle)

2019/02/28 21:55

ykleeac

C언어로 풀어봤습니다. 효율적일지는 모르겠네요. 가장 간단하게 접근할 수 있는 방식이라고 생각합니다.

#include <stdio.h>

int main(void) {
    int i, n;
    int st, fn;
    int max = 0;
    int count;

    scanf_s("%d %d", &st, &fn);
    for (i = st; i<fn; i++) {
        count = 1;
        n = i;
        while (1) {
            if (n == 1) {
                break;
            }
            if (n % 2) {
                n = 3 * n + 1;
                count++;
            }
            else {
                n /= 2;
                count++;
            }
        }

        if (count> max)
            max = count;
    }
    printf("%d\n", max);
}

2019/03/02 12:59

rook1e

def cycle(cnt,num):
    if num == 1:
        return cnt
    if num % 2 == 0:
        num = num / 2
        cnt += 1
        return cycle(cnt,num)
    else:
        num = num*3 + 1
        cnt += 1
        return cycle(cnt,num)

def cycle_range(i,j):
    max_cycle = cycle(1,i)
    for n in range(i,j+1):
        if cycle(1,n) > max_cycle:
            max_cycle = cycle(1,n)
    return max_cycle

2019/03/02 19:27

dodoman

python 3.7입니다.

s = input().split()
i = int(s[0])
j = int(s[1])

def cycleLength(n):
    length = 1
    while n != 1:
        n = n / 2 if n % 2 == 0 else n * 3 + 1
        length = length + 1
    return length

lengths = [cycleLength(n) for n in range(i, j + 1)]
print("{0} {1} {2}".format(i, j, max(lengths)))

2019/03/17 19:27

goldsmile

def cycle(i, j):
    list = []
    for x in range(i, j + 1):
        count = 1
        while x != 1:
            if x % 2 == 0:
                x = x // 2
                count += 1

            elif x % 2 != 0:
                x = x * 3 + 1
                count += 1
        list.append(count)
    print(max(list))

cycle(100,200)

2019/03/23 15:41

김성근

def cycle(x,y):

    def cyc(n):
        lst = []
        lst.append(n)
        while n != 1 and n != 0:
            if n%2 ==0 :
                n = n / 2
                lst.append(int(n))
            elif n%2 == 1:
                n = 3*n +1
                lst.append(int(n))
        return len(lst)

    leng=[]
    for n in range(x,y + 1):
        leng.append(cyc(n))
    print( x, y, max(leng) ) 

cycle(1,10)
cycle(100,200)
cycle(201,210)
cycle(900,1000)

2019/03/23 18:14

김동률

def func(n) :
    cyclelen =1
    while n>1:
        if n %2 == 0:
            n /= 2
            cyclelen +=1
        elif n %2 == 1:
            n*=3
            n+=1
            cyclelen +=1
    return cyclelen

numrange = input("확인하고 싶은 범위 입력 : ").split()
thelist=list()


for x in range(int(numrange[0]),int(numrange[1])+1):
    a = func(x)
    thelist.append(a)
print(max(thelist))

2019/03/28 16:25

박범수

파이썬 입니다.

def cycle(d, f):
    result = []
    for i in range(d,f+1):
        cnt = 1
        while i > 1:
            if i % 2 == 0:
                i = i // 2
                cnt += 1
            else :
                i =  i * 3 + 1
                cnt += 1
        result.append(cnt)
    return  max(result)

2019/04/03 15:21

김코딩

파이썬3.7 입니다 input 부분은 간단하게 메서드로 구현하였습니다.

def method(n, m):
    val = 0
    for i in range(n, m+1):
        lst = [i,]
        while lst[-1]!=1:
            lst.append(int(lst[-1]/2) if lst[-1]%2==0 else lst[-1]*3+1)
        val = len(lst) if len(lst)>val else val
    print(n, m , val)

# 입출력 예  
'''
>>> method(1,10)
1 10 20
>>> method(100,200)
100 200 125
>>> method(201,210)
201 210 89
>>> method(900,1000)
900 1000 174
'''

2019/04/04 10:46

Clifford Lindsher

import java.util.Scanner;

public class Problem3n1 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        System.out.print("두 수를 입력하시오 : ");
        int a = sc.nextInt();
        int b = sc.nextInt();

        int max = 0;
        for(int i = a; i<=b; i++){
            int x = cycle(i);
            max = x >= max? x : max;
        }

        System.out.println(max);
    }

    private static int cycle(int num){
        int count = 1;

        while(num != 1){
            if(num%2 == 0){
                num = num/2;
            }
            else{
                num = num*3 + 1;
            }
            count++;
        }

        return count;
    }
}

2019/04/07 22:50

김동수

메모이제이션 사용하여 시간복잡도 O(N) 공간복잡도 O(N)

#include <iostream>
using namespace std;
int memo[10000001];
int main()
{
    int from, to;
   memo[1] = 1;
    for(int i =2; i <= 10000000 ; i +=2)
        memo[i] = i / 2;
    for(int i = 3 ;i <= 10000000 ; i+=2)
        memo[i] = 3*i +1;

    do {
        scanf("%d %d", &from, &to);
        if(from == 0)
            break;
        int max_cnt = -1;
        int cnt;
        for(int i = from; i <= to; i++)
        {
            cnt = 1;
            int cur_i = i;
            while(cur_i != 1)
            {
                cur_i = memo[cur_i];
                cnt++;
            }

            if(max_cnt < cnt)
                max_cnt = cnt;
        }
        cout << max_cnt << endl;
    }while(true);
    return 0;
}

2019/05/01 20:17

이기준

a,b=map(int,input().split());maxx=0

for i in range(a,b+1):
    test=[]
    while i!=1:
        test.append(i)
        if i%2==1:
            i=i*3+1

        else:
            i=int(i/2)

    maxx=max(maxx,len(test)+1)

print(maxx)

2019/05/04 09:09

암살자까마귀

c/c++

int input_A = 900, input_B = 1000;
int max_count = 0;

for(int i = input_A; i <= input_B; i++){
    int count = 1;
    int temp = i;

    while(temp != 1){
        if(temp%2 == 0){
            temp = temp/2;
        }else{
            temp = (temp*3)+1;
        }
        count++;
    }
    if(max_count < count) max_count = count;
}

std::cout << "Final COUNT :: " << max_count <<std::endl;

2019/05/10 09:58

Jung Wookyeong

def f(n):
    count = 1
    while n != 1:
        count += 1
        if n%2 == 0:
            n = n // 2            
        else:
            n = 3 * n + 1
    return count

def max_cycle(m, n):
    return max([f(i) for i in range(m, n+1)])

2019/05/10 22:16

messi

i1 = int(input()) # 인풋 받기
a = 0  # 변수 만들기
while i1 != 1: # 결과가 1 이 아닐때
    if i1 % 2 == 1: # 홀수면
        i1 = i1 * 3 + 1 # *3+1 하기
        a = a + 1 # 횟수 + 1
    else: # 짝수면
        i1 = i1 / 2 # 반으로 나누기
        a = a + 1 # 횟수 + 1
print(a) 횟수 출력하기

-Made by Markelody

2019/05/29 21:59

Firelight

def problem(n):
    seq = [n]
    while 1:
        if n == 1: break
        elif n%2 == 1: n = 3*n + 1
        else: n = n//2
        seq += [n]
    return seq

i, j = map(int, input('>>>').split(','))
print(max([len(problem(n)) for n in range(i, j+1)]))

2019/05/31 12:31

이진형

#include<iostream>
using namespace std;

int main()
{
    int count;
    int maxCount = 0;
    int i, j;
    cin >> i; cin >> j;
    for (int k = i; k <= j; k++)
    {
        count = 1;
        //cout << "k : " << k << endl;
        int n = k;
        while (n != 1)
        {
            if (n % 2 == 0)
            {
                n /= 2;
                ++count;

            }
            else
            {
                n = n * 3 + 1;
                ++count;
            }
            if (maxCount < count)
                maxCount = count;
        }
    }

    cout << maxCount;
}

만들기는 했는데 문제의 목적을 모르겠군요..ㅎ

2019/05/31 21:14

와디더

import java.util.Scanner;

public class Cal3N1 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int start = 0, end = 0;
        while(scan.hasNext()) {
            start = scan.nextInt();
            end = scan.nextInt();
            System.out.print(start + "\t");
            System.out.print(end +"\t");

            int result = findMostCycleinBetween(start, end);
            System.out.println(result);
        }
        scan.close();

    }

    private static int findMostCycleinBetween(int start, int end) {
        int max = 0;
        for(int i= start; i<=end; i++) {
            int curCnt = findCycleCnt(i);
            if(max < curCnt)
                max = curCnt;
        }
        return max;
    }

    private static int findCycleCnt(int curNum) {
        int count = 0;
        while( curNum != 1) {
            if( curNum%2 == 0) {
                curNum = curNum/2;
            }else {
                curNum = curNum*3+1;
            }           
            count++;
        }
        count++;
        return count;
    }

}

2019/06/20 04:55

Seohwan Moon

def solution(a,b):
    result = [a,b]
    t = []
    for i in range(a,b+1):
        c = 1
        while(True):
            if i == 1:
                t.append(c)
                break
            if i % 2 == 0:
                i = i//2
            else:
                i = i * 3 + 1
            c+=1
    result.append(max(t))
    return result

print(solution(1,10))
print(solution(100,200))
print(solution(201,210))
print(solution(900,1000))

2019/07/17 20:42

최은미

def q(q):
    count=1
    while q !=1:
        if q%2==0:
            q=q/2
            count+=1
        else :
            q=q*3+1
            count+=1
    return count
lst=[]
a,b=map(int,input().split())
for i in range(a,b+1):
    lst.append(q(i))
print(max(lst))

2019/07/25 12:41

유선종

#3n+1 Problem


def longestCycle(first,end):

    maxCycle=1

    for num in range(first, end+1):
        tmp=num
        cycles=0
        while(tmp!=1):
            if(tmp%2==0):
                tmp=tmp//2
                cycles+=1
            else:
                tmp=3*tmp+1
                cycles+=1
        if(cycles>maxCycle):
            maxCycle=cycles
    return maxCycle+1

result=longestCycle(900, 1000)
print(result)

2019/08/01 11:39

Hwain Choi

def _3n_1_problem(N):
    if N == 0:
        raise ValueError
    elif N == 1:
        return 1
    elif N % 2 == 0:
        return _3n_1_problem(N/2) + 1
    elif N % 2 == 1:
        return _3n_1_problem(3*N+1) + 1

def _3n_1_main(i, j):
    if i >= j:
        i, j = j, i
    result = []
    for x in range(i, j+1, 1):
        result.append(_3n_1_problem(x))
    print(max(result))


if __name__ =="__main__":
    _3n_1_main(int(input()), int(input()))

2019/08/06 22:10

이우현

#include <stdio.h>

int main(void)
{
    int num1,num2;
    int maxi=0;
    int mini=1;
    scanf("%d%d",&num1,&num2);
    while(num1<=num2)
    {
        int c = num1;
        mini = 1;
        while(c!=1)
        {
            if(c%2 == 0)
                c/=2;
            else
            {
                c*=3;
                c++;
            }
            mini++;
        }
        if(mini>maxi)
        {
            maxi = mini;
        }
        num1++;
    }
    printf("%d",maxi);
    return 0;
}

2019/08/10 21:46

RADEAN STUDIO

a=list(input("정수 입력: ").split(' '))
result=[]
count=[]
for i in range(int(a[0]),int(a[1])+1,1):
    n=i
    result.append(n)
    while n!=1:
        if n%2==0:
            n=n/2
        else:
            n=n*3 +1
        result.append(n)
    count.append(len(result))
    result.clear()
print(a[0],a[1],max(count))

2019/08/14 17:02

박재욱

def proc(n):
    cnt=1
    while n != 1:
        if n%2 ==0 :
            n /= 2
            cnt +=1
        else:
            n = n*3 +1
            cnt +=1
    return cnt
def prob():
    i,j = input().split(' ')
    max_cnt=-1
    for nn in range(int(i),int(j)+1):
        if proc(nn) > max_cnt:
            max_cnt = proc(nn)
    print(max_cnt)
prob()

2019/08/15 11:33

최재학

def _3n(_input1,_input2):
    max_count=0
    for num in range(_input1,_input2):

        count = 0
        while num !=1:
            if num%2==0:
                num=num/2
            else:
                num=3*num+1
            count += 1
        if max_count< count:
            max_count=count
    print("최대싸이클 :"+str(max_count+1))

_3n(100,200)

2019/08/30 11:28

Cosu

def cycle(a):
    list1 = []
    while a > 1:
        list1.append(a)
        if  a % 2 == 0:
            a = a//2
        elif a % 2 == 1:
            a = a*3 + 1
    list1.append(1)
    return len(list1)

x = int(input("숫자를 입력하세요 : "))
y = int(input("숫자를 입력하세요 : "))
result = []
for i in range(x,y+1):
    result.append(cycle(i))
print(max(result))

2019/09/09 21:11

황수빈

PHP

$len = function(int $n, int $c = 1) use(&$len) : int {
    return $n === 1 ? $c : $len($n % 2 === 0 ? $n / 2 : $n * 3 + 1, ++$c);
};
$fn = function(int $i, int $j) use(&$len) : string {
    return sprintf("%d %d %d", $i, $j, max(array_map($len, range($i, $j))));
};
print_r($fn(1, 10)); // 1 10 20
print_r($fn(100, 200)); // 100 200 125
print_r($fn(201, 210)); // 201 210 89
print_r($fn(900, 1000)); // 900 1000 174

2019/09/11 14:10

d124412

def cycle(n):
    count = 1
    while n != 1:
        if n % 2 == 0:
            n = n / 2
            count += 1
        else:
            n = n*3 + 1
            count += 1
    return count

i = 100
j = 200
print(max(cycle(x) for x in range(i, j)))

2019/09/17 16:25

Dreaming Pug

def cycle_long(n):
    i=1
    while n!=1:
        if n%2==0:n//=2
        else: n=3*n+1
        i+=1
    return i

def max_c_l(m, n):
    M=0
    for k in range(m, n+1):
        if M<cycle_long(k): M=cycle_long(k)
    return M

a=input('Enter the nums: ')
b=list(map(int,a.split(' ')))
print('{0:<6} {1:<6} {2:<6}'.format(b[0], b[1], max_c_l(b[0],b[1])))

2019/09/19 16:52

돔돔

i, j = input("input : ").split(" ")    #i, j를 입력으로 받음
result = 0                             #최대 사이클 수를 result로 설정
for k in range(int(i), int(j)+1) :
    count = 1
    while k != 1 :                     #사이클 수를 계산. i이상 j이하의 수 k가 짝수이면 2로 나누고, 홀수이면 3k+1로 갱신
        if k%2 == 0 :
            k = int(k/2)
            count += 1
        else :
            k = int(3*k+1)
            count += 1
    if count > result :                #사이클 수(count)가 현재 최대치(result)를 넘으면 result에 최대치 갱신
        result = count
print(result)

결과

input : 201 210 89

input : 900 1000 174

2019/09/25 16:15

GG

def makeonecycle(number):
    cnt = 1
    while True :
        if number == 1:
            break
        elif number % 2 == 0:
            number = number / 2
            cnt += 1
        else :
            number = 3 * number + 1
            cnt += 1
    return cnt

start_num, end_num = map(int,input('Enter the start number and end number : ').split(' '))
result = [makeonecycle(number) for number in range (start_num, end_num+1)]
print(max(result))

2019/10/02 14:15

nhoeal

def Problem(n):
    count = 1
    if n == 1:
        return n
    while n != 1:
        if n % 2 ==0:
            n = n/2
            count +=1           
        else :
            n = n*3+1
            count +=1       
    return count

x = int(input("첫번째 수 : "))
y = int(input("두번째 수 : "))
result = 0
for i in range(x,y+1):
    data = Problem(i)
    if data > result :
        result = data
print(x,y,result)

2019/10/24 23:41

semipooh

#include <iostream>
#include <climits>
using namespace std;

int max_cycle(int i,int j){
    int cnt=1,M=INT_MIN;
    int temp;

    for(int k=i;k<=j;k++){
        temp=k;
        cnt=1;

        while(temp!=1){
            if(temp%2==0)
                temp/=2;
            else
                temp=(temp*3)+1;
            cnt++;
        }
        if(M<cnt)
            M=cnt;
    }
    return M;
}

int main(){
    int i,j,Mlength;
    cin>>i>>j;

    Mlength=max_cycle(i,j);

    cout<<Mlength;

    return 0;
}

2019/10/26 12:36

저택벚꽃

import java.util.*;
public class 삼n더하기일Problem {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String[] lines = scan.nextLine().split(" ");
        int[] nums = Arrays.stream(lines).mapToInt(Integer::parseInt).toArray();
        int[] max = {0};
        for(int i=nums[0]; i<nums[1]+1; i++) {
            int num=i;
            int count = 1;
            while(true) {
            if(num == 1) {
                if(max[0]<count) {
                    max[0]=count;
                }
                break;
            }
            else if(num%2==0) {
                num = num/2;
                count++;
                }
            else {
                num = num*3+1;
                count++;
                }
            }
        }
        System.out.println(nums[0]+" "+nums[1]+" "+max[0]);
    }
}

2019/11/17 15:15

big Ko

sr = {}
n1 = 100
n2 = 200
max = 0

for i in range(n1,n2+1):
  cnt = 1
  n3 = i
  while(True):
    cnt = cnt+1
    if n3%2==0 : n3 = n3/2
    else : n3 = n3*3+1
    if n3 == 1:
      if max lt cnt : max = cnt
      sr[cnt] = i
      break;
print max
print sr.get(max)

파이썬으로 풀었습니다 최대 사이클 길이와 해당 값이에요

2019/11/26 14:12

오오옹

파이썬 3.6 입니다

def steps_till_one(n):
    steps = [n]
    while n != 1:
        if n % 2 == 0:
            n = n / 2
        else:
            n = (3 * n) + 1
        steps.append(int(n))
    return len(steps)

def max_steps(i, j):
    steps_list = []
    for n in range(i, j + 1):
        steps_list.append(steps_till_one(n))
    return max(steps_list)

print(max_steps(1, 10))
print(max_steps(100, 200))
print(max_steps(201, 210))
print(max_steps(900, 1000))

2019/11/27 15:00

vkospi

def prob(k) :
    length = 0
    while k != 1 :
        if k%2 == 0 :
            k /= 2
        else :
            k = 3*k+1
        length += 1
    return length+1
inp, res = list(map(int, input("INPUT : ").split(" "))), []
for a in range(min(inp[0], inp[1]), max(inp[0], inp[1])+1) :
    res.append(prob(a))
print(max(res))

결과

INPUT : 900 1000
174

INPUT : 100 10000
262

2019/12/06 17:02

GG

파이썬3입니다.

def my_func1(n):
  m = 1
  while n != 1:
    if n % 2 == 0:
      n *= 0.5
      m += 1
    else:
      n = (n * 3) + 1
      m += 1
  return m

def my_func2(i, j):
  result = [my_func1(n) for n in range(i, j+1)]
  return max(result)

2019/12/21 15:27

Sean

def get_cycle_len(n):
    cycle_list = [n]
    while n > 1:
        if n % 2 == 0:
            n = n / 2
        else:
            n = 3 * n + 1
        cycle_list.append(int(n))
    return len(cycle_list)


def max_cycle(i, j):
    mc = max([get_cycle_len(x) for x in range(min(i, j), max(i, j) + 1)])
    return mc


print(max_cycle(100, 200))

2020/01/03 14:01

김민기

def maxcycle(i,j):
    cycle=[]
    for n in range(i,j+1):
        nlst=[n]
        while n!=1:
            if n%2==0:
                n=int(n/2)
            else:
                n=(3*n)+1
            nlst.append(n)
        cycle.append(len(nlst))
    return max(cycle)
print(maxcycle(900,1000)) #174

2020/01/13 15:40

박시원

python 2.7.16

print('set the range: ')
fir = int(input('start >> '))
sec = int(input('end >> '))

a = range(fir,sec+1)
record = 1

for i in a:
    n = i

    empty = [n]


    while(n != 1):
        if (n % 2 == 0):
            n = int(n/2)
            empty.append(n)
        elif (n % 2 != 0):
            n = int((n*3)+1)
            empty.append(n)

    longest = len(empty)

    if longest > record:
        record = longest

print(record)

2020/01/15 14:10

Jung Marco

Javascript(ES6)...

`숫자 n 을 넣으면 수열의 사이클 길이 length 를 [n, length] 형태로 반환하는 함수 seq 구현, 반복문을 통해 함수의 결과를 넣은 배열을 생성한 뒤, 배열 안에서 length 길이가 가장 큰 것을 출력`;

// 순열의 길이를 반환하는 seq 함수
function seq(n) {
    let _n = n;
    let length = 1;

    while(true) {
        _n = (_n % 2 == 0) ? ~~(_n / 2) : 3 * _n + 1;    // ~~( x ) 는 x 에서 소수점 이하 절사 반환
        length++;

        if(_n == 1) { break; }
    }

    return [_n, length];
}

// 숫자 사이의 수들을 seq 함수에 넣어서 배열로 생성, 이후 사이클 길이가 가장 큰 것을 출력하는 함수
function print_seq(min, max) {

    let result = [];
    for(let i = min; i < max + 1; i++) {
        result.push(seq(i));
    }

    // 사이클 길이가 가장 큰 것이 앞으로 오도록 정렬
    result.sort((a, b) => -(a[1] - b[1]));

    console.log(min, max, result[0][1]);
}

print_seq(1, 10);        // 1 10 20
print_seq(100, 200);     // 100 200 125
print_seq(201, 210);     // 201 210 89
print_seq(900, 1000);    // 900 1000 174

Python 3...

# 숫자 n 을 넣으면 (n, length) 반환 함수
def seq(n):
    length = 1
    _n = n
    while True:
        length += 1
        _n = _n // 2 if _n % 2 == 0 else 3 * _n + 1
        if _n == 1:
            break
    return n, length

# 범위 안에서 seq 의 length 결과가 가장 큰 케이스 출력
def print_seq(min, max):
    result = []
    for n in range(min, max + 1):
        result.append(seq(n))

    result.sort(key = lambda x: x[1], reverse = True)

    print(min, max, result[0][1])

print_seq(1, 10)        # 1 10 20
print_seq(100, 200)     # 100 200 125
print_seq(201, 210)     # 201 210 89
print_seq(900, 1000)    # 900 1000 174

2020/01/17 14:35

tedware

def cycle(n):
    count = 1
    while n > 1:
        if n % 2 == 0:
            n = n/2
            count += 1
        else:
            n = 3*n + 1
            count += 1
    return count

def max_cycle(i,j):
    cycle_list = []
    for n in range(i,j):
        cycle_list.append(cycle(n))
    print(max(cycle_list))

max_cycle(1,10)

2020/02/05 21:42

꺼비

import java.util.Scanner;

public class CycleProblem {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        CycleProblem cp = new CycleProblem();

        System.out.print("정수를 입력하시오 ");         //정수를 입력받음
        int input1 = sc.nextInt();
        int input2 = sc.nextInt();
        int max = cp.CycleLength(input1);           //사이클 길이 최대 값 초기화
        for(int i = input1; i<=input2; i++) {       //사이클 길이 최대 값 설정
            if(max == cp.CycleLength(i)) {          
                continue;
            }
            if(max < cp.CycleLength(i)) {           //사이클 길이가 최대일때
                max = cp.CycleLength(i);
            }
        }
        System.out.println("결과값: "+max);
        sc.close();
    }

    public int CycleLength(int input) {
        int count = 0;
        if(input == 1) {
            return count +1;
        }
        if(input % 2 == 0) {                        //입력값이 짝수일때
            count ++;
            return count+=CycleLength(input/2);
        }
        else {                                      //입력값이 홀수일때   
            count ++;
            return count+=CycleLength(3*input+1);
        }
    }
}

재귀함수를 이용하여 문제를 해결했습니다.

2020/02/07 00:21

김강민

파이썬 3.8
def sequence(i,j):
    max = 0
    for t in range(i,j+1):
        array = []
        array.append(t)
        while array[-1] != 1:
            if array[-1] %2==0:
                array.append(array[-1]/2)
            else:
                array.append(array[-1]*3+1)
        if len(array) > max:
            max = len(array)
    return max

a, b = input().split(' ')
a, b = int(a),int(b)
print(a, b, sequence(a,b))

2020/02/22 23:29

카레맛카레

def cypro(a):

    cl = 1

    while a != 1:

        if a%2 == 0:

            a = (a/2)

            cl+=1

        else :

            a = (3*a +1)

            cl+=1

    return cl

cycle = []

i = int(input('i = '))

j = int(input('j = '))

for k in range(i,j+1):

    cycle.append(cypro(k))


print(max(cycle))



2020/03/01 21:41

HyukHoon Kim

i = int(input("입력: "))
j = int(input("입력: "))

z = []
t = []

for a in range(i, j+1):
    while True :
        if a % 2 == 0:
            a = a/2
            z.append(a)
        elif a % 2 == 1 and a != 1:
            a = a*3+1
            z.append(a)
        else:
            z.append(a)
            break

    t.append(len(z))        
    z = []

print(max(t))    

2020/03/02 23:05

김희준

python 3.8

i=100             # input()함수로 2개 변수 받기
j=200
maxlen=0     # 숫자별 총갯수 최대값 찾기
for a in range(i,j+1):
   b=[a]          #숫자별 리스트 정렬
   while a != 1 :
       if  a %2 != 0 :
            a=a*3+1
       else:
            a=int(a/2)
       b.append(a)
   if maxlen <= len(b):
       maxlen = len(b)
print(i,j,maxlen)    # i,j 사이의 숫자 리스트 최대값 찾기

2020/03/02 23:46

mr. gimp

global cycle_

def cycle(n):
        global cycle_
        cycle_ = 1
        while n != 1:
                if n % 2 == 0:
                        n = n / 2
                        cycle_ += 1
                else:
                        n = n * 3 + 1
                        cycle_ += 1
        return cycle_

global cycle_list 
cycle_list = []

def solve(i, j):
        for num1 in range(i, j+1):
                result = cycle(num1)
                result = str(result)
                cycle_listsolve(1.append(result)

        for num2 in range(0, len(cycle_list)):
                cycle_list[num2] = int(cycle_list[num2])

        return max(cycle_list)

2020/03/09 23:19

PythonLover&Master_JK73

def even(N):
    return N / 2

def oddnumber(N):
    return (3*N)+1

def loop(N):
    check = N
    find = 1
    while(True):
        if check == 1:
            return find
        if check % 2 == 0:
            check = even(check)
            find += 1
        elif check % 2 == 1:
            check = oddnumber(check)
            find += 1

def main(n,m,final):
    for i in range(n,m+1):
        final.append(loop(i))
    return max(final)


N = list(map(int,input().split()))
finish = list()
print(main(N[0],N[1],finish))


2020/03/11 14:51

BlakeLee

i=int(input())
j=int(input())
max=0

for n in range(i,j+1):
  times=1

  while (n>1):
    times=times+1
    if n%2==0:
     n=n/2
    else:
      n=(n*3)+1 

  if times>max:
    max=times

print(max)

2020/03/12 09:50

Buckshot

import java.util.Scanner;

public class testing {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int count = 1;
        int counttmp=0;
        System.out.println("수 입력1 : ");
        int n = scanner.nextInt();
        System.out.println("수 입력2 : ");
        int l = scanner.nextInt();
        int tmp = n;
        for(;n<=l;n++){

            while(tmp!=1){
                if(tmp%2==0){
                    tmp=tmp/2;
                }
                else if(tmp%2==1){
                    tmp=tmp*3+1;
                }
                count++;
            }
            if(counttmp<count){
                counttmp = count;
            }
            count=1;
            tmp=n+1;
        }
        System.out.println(counttmp+"번 반복했습니다.");
    }
}

2020/03/13 23:25

Reflelia

i,j= map(int, input().split())
m=1

for n in range(i,j+1):
    l=[n]
    while 1:
        if n%2==0: n=n/2
        else:n=n*3+1
        l.append(n)
        if n==1: break

    if m<len(l):
        m=len(l)

print(i,j,m)

2020/03/14 15:49

황예진

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
어떤 정수 n에서 시작해, n이 짝수면 2로 나누고, 홀수면 3을 곱한 다음 1을 더한다. 
이렇게 해서 새로 만들어진 숫자를 n으로 놓고, n=1 이 될때까지 같은 작업을 계속 반복한다. 
예를 들어, n=22이면 다음과 같은 수열이 만들어진다. 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

n이라는 값이 입력되었을때 1이 나올때까지 만들어진 수의 개수(1을 포함)를 n의 사이클 길이라고 한다. 
위에 있는 수열을 예로 들면 22의 사이클 길이는 16이다. i와 j라는 두개의 수가 주어졌을때, 
i와 j사이의 모든 수(i, j포함)에 대해 최대 사이클 길이를 구하라.

입력 예
1    10
100  200
201  210
900  1000

출력 예
1    10    20
100  200   125
201  210   89
900  1000  174
*/

namespace A {
    int count;
}

void Recall(int n) {
    ++A::count;
    if (n == 1)return;

    if (n % 2 == 0)Recall(n / 2);
    else Recall(3 * n + 1);
}

void Func(int b, int e) {
    vector<int> v;
    for (int i = b; i <= e; i++) {
        A::count = 0;
        Recall(i);
        v.push_back(A::count);
    }
    sort(v.rbegin(), v.rend());
    cout << b << "\t" << e << "\t" << v.front() << endl;
}

int main() {
    Func(1, 10);
    Func(100, 200);
    Func(201, 210);
    Func(900, 1000);
}

2020/03/21 17:21

++C


def func_cnt(num):
    count = 1
    while num != 1:
        if num % 2 == 0: num = num / 2
        else: num = 3 * num + 1
        count += 1
    return count

res_list = []
num1, num2 = map(int, input('두개의 숫자를 차례로 입력해주세요(예:1 10): ').split())
for i in range(num1, num2+1):
    res_list.append(func_cnt(i))

res_list.sort(reverse=True)
print(num1, ' ', num2, ' ', res_list[0])

2020/04/03 20:40

잘해보자

i = 900
j = 1000
rank = []

for t in range(i,j+1) :
    count = 1
    while t != 1 : 
        if t % 2 == 0 : t = t/2
        else : t = t*3+1 
        count += 1
    rank.append(count)

print(i,j,max(rank))

2020/04/09 16:11

Polarbear1111

def cycle_load(cyc1, cyc2):
    dict_cycle = {}
    for cycle in range(cyc1, cyc2+1):
        cycle_cnt = 0
        cal_cycle = cycle
        #if cycle_cnt == 0 and cal_cycle == 1:
        #    cycle_cnt = 1
        #else:
        while cal_cycle != 1:
            cycle_cnt += 1
            if cal_cycle % 2 == 0:
                cal_cycle = cal_cycle / 2
            else:
                cal_cycle = (cal_cycle * 3) + 1

        cycle_cnt += 1
        dict_cycle[cycle] = cycle_cnt
    return max(dict_cycle.values())


def main():
    cyc1, cyc2 = map(int, input('입력할 사이클 길의 최소, 최대값을 입력하세요: ').split())
    print(cycle_load(cyc1, cyc2))

if __name__ == '__main__':
    main()

2020/04/13 12:37

Hwaseong Nam

def problem(first, second):
    max_list = []
    for i in range(first, second+1):
        max_list.append(cycle(i))
    return max(max_list)

def cycle(n):
    result_list = [n]
    while n != 1:
        if n % 2 ==0: # 짝수면
            n = n/2
            result_list.append(int(n))
        else: # 홀수면
            n = (n * 3) + 1
            result_list.append(int(n))
    return len(result_list)

print(problem(1, 10))
print(problem(100, 200))
print(problem(201, 210))
print(problem(900, 1000))

2020/04/19 23:14

ptjddn95

while True:
    num=input("종료하시려면 0,0 입력").split(" ")
    if num[0]=='0' and num[1]=='0':
        break
    cycle=[]
    for i in range(int(num[0]),int(num[1])+1):
        z=i
        count = 1
        while z!=1:
            if z%2==0:
                z/=2
            else:
                z=z*3+1
            count+=1
        cycle.append(count)
    print("{}   {}   {}".format(int(num[0]),int(num[1]),max(cycle)))

2020/04/23 23:01

kim center

def next_n(n):
    if n % 2 == 0 : return n // 2
    else: return 3 * n + 1
def cycle_n(n):
    count = 0
    while n != 1:
        n = next_n(n); count += 1
    return count + 1

i, j = map(int, input().split())
print(max([cycle_n(x) for x in range(i, j+1)]))

2020/04/24 15:23

YB Jung

a=int(input('1st number : '))
b=int(input('2nd number : '))

li=[]
for n in range(a,b):
    c=0
    maxx=0
    while n>1:
        if n%2==0:
            n=n/2
            c+=1
        else:
            n=3*n+1
            c+=1
    li=li+[c+1]

print(li)
li2=sorted(li)
print(li2)
print(li2[-1])

2020/04/27 23:05

양양짹짹

def cyclelength(n):
    trial = 1
    while n != 1:
        if n % 2 == 0:
            n = n/2
        else :
            n = 3*n+1
        trial += 1
    return trial
def max_cyclelength(i, j):
    return max(cyclelength(d) for d in range(i, j+1))

2020/04/28 22:11

최민기

def find_max_length(i, j):
    def find_length(n):
        seq_list = [n]
        while seq_list[-1] > 1:
            if seq_list[-1] % 2 == 0:
                seq_list.append(seq_list[-1] / 2)
            else:
                seq_list.append(seq_list[-1] * 3 + 1)
        return len(seq_list)
    return max([find_length(i) for i in range(i, j + 1)])

2020/05/08 21:52

김준혁


def cyc(n):
    a = [n,]
    while True:
        if n%2 ==0:
            n = n//2
            a.append(n)
        else:
            n = 3*n+1
            a.append(n)
        if n == 1:
            break
    return len(a)
i = int(input())
j = int(input())

b = []
for p in range(i,j+1):
    b.append(cyc(p))

print(max(b))

2020/05/11 17:01

Money_Coding

n1, n2 = input('type two integer numbers with space :').split()
n1, n2 = int(n1), int(n2)

def cycle_len(n):
    n_cycle=1
    while n!= 1:
        if n%2 == 0:
            n = n/2            
        elif n%2 == 1:
            n = n*3+1
        n_cycle +=1
    return n_cycle

n_cycle = [cycle_len(i) for i in range(n1,n2+1)]
print(n1, n2, max(n_cycle))

2020/05/29 13:59

aryagaon

i=int(input())
j=int(input())
b=[]
for n in range(i,j+1):
    a=[n]
    while int(a[-1]) != 1:
        if int(a[-1])%2==0:
            c=int(a[-1])//2
            a.append(c)
        else:
            c=3*int(a[-1])+1
            a.append(c)
    b.append(len(a))
b.sort()
print(b[-1])

2020/06/18 02:25

SREBP1c

파이썬3입니다.

#set max number and min number
inputNumber = input('set min number and max number with blank. ').split( )
minNumber = int(inputNumber[0])
maxNumber = int(inputNumber[1])

#processing cycle length list
def CycleLength(n) :
    cLength = 1
    while n != 1 :
        if n % 2 == 0 :
            cLength += 1
            n /= 2
        else :
            cLength += 1
            n = n*3+1
    return cLength

cycleNumbers = { x : CycleLength(x) for x in range(minNumber, maxNumber+1) } 

print(f'{minNumber} {maxNumber}  {max(cycleNumbers.values())}')
#select n having max cycle length

2020/06/18 09:52

누마루

def np1(i, j) :
    a=[0]
    for x in range(i, j+1):

        cnt = 1
        while(x!=1):
            if x%2 == 0 :
                x=x/2
                cnt+=1
            elif x%2 !=0 :
                x=x*3+1
                cnt+=1
        if a[0]<cnt :
            a[0]=cnt
    print(a[0])

2020/06/23 18:57

YSM

1회 실행하도록 하기

public class three_game {

    public int count=0;

    public void game(int a) {
        count=1;
        while(true)
        {
            count++;
            if(a%2==0){
                a=a/2;
                if(a==1)
                    break;}
            else
                a= 3*a +1;

        }
    }
}


public class main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        three_game game = new three_game();

        int max=0;
        int a,b;

            a = scan.nextInt();
            b = scan.nextInt();
            for(int i=a;i<=b;i++)
            {
                game.game(i);
                if(game.count>max)
                    max=game.count;
            }

            System.out.println(max);
    }

}


2020/07/18 18:58

허병우

while True:

    i = input(" i값 입력 > ")
    j = input(" j값 입력 >")

    try:
        i= int(i)
        j = int(j)
    except:
        print('정수 값을 입력하시오.')


    def n3(num):
        L =list()
        L.append(num)
        while num !=1:
            if num%2 == 0:
                num  =int(num/2)
                L.append(num)
            else:
                num = num*3+1
                L.append(num)
        return len(L)

    new_list = sorted([n3(x) for x in range(i, j+1)], reverse =True)

    print(str(i)+" "+str(j)+" "+str(new_list[0]))

2020/07/27 15:53

김병관

inp = list(map(int,input("두 값을 입력하시오: ").split()))
i,j = int(min(inp)), int(max(inp))
max_cyc = 0
for n in range(i,j+1):
    cnt = 1
    while n != 1:
        if n%2 == 0:
            n = n/2
        else:
            n = 3*n + 1
        cnt += 1
    if cnt >= max_cyc:
        max_cyc = cnt
print(i,'\t',j,'\t',max_cyc)

2020/08/27 15:42

Bbb Aaa

import java.util.Scanner;

public class test6 {
    static int time = 0;
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("첫 수를 입력하시오 : ");
        int input_a = scanner.nextInt();

        int max_time = 0;

        System.out.print("둘째 수를 입력하시오 : ");
        int input_b = scanner.nextInt();
        if(input_b < input_a){
            int temp = input_a;
            input_a = input_b;
            input_b = temp;
        }

        for(int i = input_a ; i < input_b; i++) {
            Cycle_length(i);
            if(max_time < time) max_time = time;
            time = 0;
        }

        System.out.println(max_time);
    }

    public static int Cycle_length(Integer a) {
        time++;
        if(a == 1) {
            return 1;
        }else if(a % 2 == 0) {
            return Cycle_length(a/2);
        } else {
            return Cycle_length(3 * a + 1);
        }
    }
}

2020/09/15 18:58

nazunamoe

def cicle_count(n):
    count = 1
    while n != 1:
        count += 1
        if n == 1:
            break
        elif n % 2 == 0:
            n = n / 2
        else:
            n = n * 3 + 1
    return count


i = int(input('정수를 입력하세요 :'))
j = int(input('정수를 입력하세요 :'))
longest_cicle = 0

for x in range(i, j+1):
    if cicle_count(x) >= longest_cicle:
        longest_cicle = cicle_count(x)
print(longest_cicle)

2020/09/18 03:01

hwang sungjo

#include <stdio.h>

int calc(int a);

int main()
{
    int i,l,a,b;

    scanf("%d %d",&a,&b);

    for(i=a;i<=b;i++)
    {
        calc(i);
        if(calc(i)>l)
            l=calc(i);
    }
    printf("%d",l);
    return 0;
}

int calc(int a)
{
    int c=1;
    while(1)
    {
        if(a==1)
            break;
        else if(a%2==1&&a!=1)
        {
            a=a*3+1;
            c++;
        }
        else
        {
            a=a/2;
            c++;
        }
    }

    return c;
}   

항상 하던 C

2020/10/03 22:39

June

i = int(input("i = \n"))
j = int(input("j = \n"))
def MaxCycle(a,b) :
    cycle = 1
    for k in range(a,b+1) :
        history = [k]
        while k != 1 : 
            if k%2 == 0 :
                k = k/2
                history.append(k)

            else :
                k = k*3 + 1
                history.append(k)
        if cycle < len(history) :
            cycle = len(history)
    return cycle

print MaxCycle(i,j)

2020/10/18 00:26

Centro

def cycleLen(a,b):
    result = []
    for i in range(a, b):
        temp = [i]
        while i != 1:
            if i % 2 == 0:
                i /= 2
                temp.append(int(i))
            else:
                i = 3 * i + 1
                temp.append(int(i))
        result.append(len(temp))
    print(max(result))


cycleLen(1, 10)
cycleLen(100, 200)
cycleLen(201, 210)
cycleLen(900, 1000)

2020/11/24 15:13

김우석

def cycle(num):
    temp = int(num)
    result = []
    result.append(temp)
    while temp != 1:
        if temp % 2 == 0:
            temp = temp/2
            result.append(int(temp))
        else:
            temp = 3*temp + 1
            result.append(int(temp))
    return len(result)

def max_cycle(num1, num2):
    maximum = 0
    for i in range(num1, num2+1):
        if cycle(i) > maximum:
            maximum = cycle(i)
    return maximum

print(max_cycle(1,10))
print(max_cycle(100,200))
print(max_cycle(201,210))
print(max_cycle(900,1000))

2020/12/04 09:59

DSHIN

package main;

import java.awt.MultipleGradientPaint.CycleMethod;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        Main m = new Main();
        System.out.println(m.Cycle(num1, num2));
    }
    int Cycle(int num1,int num2) {
        int numCnt=1;
        int max = 0;
        //i for num1,num2사이의 수 를 반복 해준다
        for (int i = num1; i <= num2; i++) {
            //j for문은 i 값 즉 대입하는 값을 하나씩 넣기 위해서 중첩 반복문을 사용 
            for (int j = i; j !=1;) {
                numCnt++;
                if(j%2==0) {
                    j=j/2;
                }else if(j%2==1) {
                    j = 3*j+1;
                }
            }
            System.out.println(i+"의 수"+numCnt);
            if(numCnt>max) {
                max = numCnt;
            }
            numCnt =1;

        }
        return max;
    }
}

2020/12/11 00:26

김준혁

def numa(a):

  count=1

  while a!=1:

    if a%2==0:

      a=a/2

      count+=1

    else:

       a=a*3+1

      count+=1

  return count

def numberint(a,b):

  max=0

  for i in range(a,b+1,1):

    if numa(i)>max:

      max=numa(i)

  print("{0}    {1} {2}".format(a,b,max))

numberint(1,10)

numberint(100,200)

2020/12/14 16:31

전준혁

파이썬 3.7.2 버전입니다.

def foo(num):
    cycle_count = 1

    while num != 1:
        cycle_count += 1

        if num%2 == 0 :
                num = num/2
        else:
            num = num*3 + 1

    return cycle_count

MIN_NUM = int(input('최대 사이클 횟수를 구하고 싶은 숫자들의 첫번째 숫자를 입력해주세요: '))
MAX_NUM = int(input('최대 사이클 횟수를 구하고 싶은 숫자들의 마지막 숫자를 입력해주세요: '))
cycle_count_list = [foo(num) for num in range(MIN_NUM, MAX_NUM+1)]
print(max(cycle_count_list))

2020/12/15 16:21

최병찬

def Maxlen(x1,x2):
    lo = min(x1,x2)
    up = max(x1,x2)
    List =[]
    for i in range(lo,up+1):
        count = 1
        while i!=1:
            if i%2==0:
                i//=2
            else :
                i = 3*i + 1
            count+=1
        List.append(count)
    return max(List)

2021/01/03 10:57

hankyu

def max_len(i,j):
    len_list=[]
    for n in range(i,j+1):
        n_list=[n]
        while True:
            if n==1:
                break
            if n%2==0:
                n=int(n/2)
                n_list.append(n)
            else:
                n=3*n+1
                n_list.append(n)
        len_list.append(len(n_list))

    print(max(len_list))

max_len(100,200)

2021/01/14 00:01

dong hoon

def cypro(k):
    cl=1
    while k != 1:
        if k%2==0:
            k=k/2
            cl+=1
        else:
            k=3*k+1
            cl+=1
    return cl

i=int(input('INPUT MIN NUM : '))
j=int(input('INPUT MAX NUM : '))
t=0
arw=[]

for t in range(i,j+1):
    arw.append(cypro(t))
print(max(arw))

2021/01/19 12:07

김지원

파이썬 3.9.1입니다.

def cycle(n):
    cnt  = 0
    while not n == 1:
        cnt += 1
        if n % 2 == 0:  n /= 2
        else:   n = 3 * n + 1
    return cnt + 1

while True:
    text = input().split(' ')
    i = int(text[0])
    j = int(text[1])
    print(i, j)
    maxcycle = max([cycle(x) for x in range(i, j+1)])
    print(i, j, maxcycle) 

2021/01/20 13:23

devlop

q=[]
for a in range(900,1000):
    line=[a]
    while a != 1:
        if a%2==0:
            a=a//2
            line.append(a)
        else:
            a=a*3+1
            line.append(a)
        q.append(len(line))

print(max(q))

input 대신에 range안에 알고싶은 숫자를 넣었습니다

2021/01/26 23:05

fox.j

def cycle_number(n):
    list1 = [n]
    while list1[-1] != 1:
        p = list1[-1]
        if p % 2 == 0:
            list1.append(p//2)
        else:
            list1.append(p * 3 + 1)
    return len(list1)

def max_cycle_number(i, j):
    max = cycle_number(i)
    for q in range(i, j):
        if cycle_number(q+1) > max:
            max = cycle_number(q+1)
    return max

2021/01/27 22:40

팝코니

i, j = map(int, input("Input Numbers: ").split())

def cycle_length(n):
    count = 1
    while n != 1:
        count += 1
        n = int(n/2) if n % 2 == 0 else 3*n+1
    return count

lengths = [cycle_length(k) for k in range(i, j+1)]

print('{0:<5d}{1:<5d}{2:<5d}'.format(i, j, max(lengths)))

2021/02/01 18:45

Ha

let num=prompt('두개의 정수를 공백으로 구분하여 입력','').split(' ');
    num=num.map((el)=>Number(el));
    let count=1;

    for (let i = num[0]; i <num[1]; i++) {
        let cnt=1;
        let n=i;
        while(n>1){
            if(n%2==0){
                n=n/2;
            }
            else{
                n=n*3+1;
            }
            cnt++;
            if(count<cnt){
                count=cnt;
            }
        }
    }
    document.write(count)


2021/02/15 15:10

wldus

def func(i,j):
    countList = []

    for n in range(i,j+1):
        count = 0
        while n > 1:
            # 짝수
            if n % 2 == 0:
                n = n / 2
                count += 1
            # 홀수
            else:
                n = n*3 + 1
                count += 1

        # 1이 될때도 count에 포함
        if n == 1:
            count += 1
        countList.append(count)

    return print(max(countList))

func(1,10) # 20
func(100,200) # 125
func(201,210) # 89
func(900,1000) #174

2021/02/22 14:51

지누

def cycle(e):
    count=1
    while e!=1:
        if e % 2 == 0:
            e = e/2
            count += 1
        if e % 2 == 1:
            e = (e*3) + 1
            count += 1
    return count

i = int(input('입력'))
j = int(input('입력'))
result=[cycle(x) for x in range(i, j+1)]

print(max(result))

맞는 풀이인 것 같은데 연산 시간이 굉장히 오래 걸리네요. 무엇이 문제일까요?

2021/03/17 09:33

최우진

def fx(n):
  if n %2==0:
    return n/2
  else:
    return 3*n+1


def len(n):
  k=n
  m=1

  while(1):
    if fx(k)==1:
      m+=1
      break
    else:
      k=fx(k)
      m+=1
  return m


n1=int(input("수입력:"))
n2=int(input("수입력:"))

max=len(n1)
for i in range(n1,n2+1):

  if len(i) > max:
    max = len(i)

print(max)

2021/04/18 22:52

장래희망파이썬마스터

def makeAns(i, j):
    long = 0
    def makeList(num):
        list1 = [num]
        while True:
            if num % 2 == 0:
                num = int(num / 2)
            else:
                num = (num * 3) + 1
            list1.append(num)
            if num == 1:
                break
        return len(list1)

    for k in range(i, j+1):
        if makeList(k) > long:
            long = makeList(k)
    print(str(i) + "    " + str(j) + "  " + str(long))


makeAns(1, 10)
makeAns(100, 200)
makeAns(201, 210)
makeAns(900, 1000)

결과
1 10 20
100 200 125
201 210 89
900 1000 174

2021/04/21 16:06

와장창

input_a,input_b = map(int,(input().split()))

def create_num_arry(inp):
    num_arr =[]
    while inp != 1:
        num_arr.append(inp)        
        if inp%2 == 0:
            inp = int(inp/2)
        else:
            inp = int((inp*3)+1)            
    num_arr.append(1)
    return num_arr

def getProblemMax(x,y):
    c = []
    for i in range(x,y+1):
        c.append(len(create_num_arry(i)))
    return max(c)   

output_no = getProblemMax(input_a,input_b)
print("{} {} {}".format(input_a,input_b,output_no))

2021/04/28 13:53

최태호

a = int(input())
b = int(input())
max_cycle=0
for i in range(a, b+1):
    cycle = 1
    while i != 1:
        if i%2 == 0:
            i = i/2
        else:
            i = 3*i + 1
        cycle += 1
    if max_cycle < cycle:
        max_cycle = cycle

print(max_cycle)

2021/05/10 15:32

치코리타

print('x에서 y까지의 3n+1 Problem')

x = int(input('x:'))
y = int(input('y:')) 
p = []

for n in range(x,y+1):
    l = []
    while n>0 :
        if n==1:
            l.append(n)
            break
        elif n%2==0:
            l.append(n)
            n = n/2
        elif n%2==1:
            l.append(n)
            n = 1 + n*3
    p.append(len(l))
print(f'최대사이클 : {max(p)}회')

2021/05/26 09:00

약사의혼자말

def cycle(n):
    times = []
    while n > 1:
        if n%2 == 0:
         n = n//2
         times.append(n)
        else:
          n = n*3+1
          times.append(n)
    return len(times)+1

k = []
a, b = map(int,input().split(' '))
for i in range(a,b+1):
    k.append(cycle(i))
print(a,b,max(k))

2021/05/30 18:05

ss2663

#codingdojing_3n+1_problem_re
# n이 짝수면 /2, 홀수면 3n+1 -> n = 1일 때까지

def threeN1(n,count): #함수이름 숫자부터 x

    count += 1

    if n == 1:
        return count
    elif n % 2 == 0:
        return threeN1(n//2, count)
    else:
        return threeN1(3*n+1, count)

for j in range(eval(input('number of rep: '))):
    a, b = map(int,input('a b (a < b): ').split())
    print(a, b, max([threeN1(i, 0) for i in range(a, b+1)]))

2021/07/21 15:45

Jaeman Lee

파이썬 3.8.10으로 작성되었습니다.

def process(n):
    if n % 2 == 0:
        return n / 2
    else:
        return n * 3 + 1


def get_cycle_length(n):
    result = []
    while(n != 1):
        n = int(process(n))
        result.append(n)
    return len(result) + 1


def get_maximum_cycle_length(i, j):
    length_list = []
    for n in range(i, j + 1):
        length_list.append(get_cycle_length(n))

    return max(length_list)


if __name__ == '__main__':
    print(get_maximum_cycle_length(1, 10))
    print(get_maximum_cycle_length(100, 200))
    print(get_maximum_cycle_length(201, 210))
    print(get_maximum_cycle_length(900, 1000))

2021/08/10 17:08

baek choi

i, j = input('숫자 두 개를 입력하세요: ').split() i = int(i) j=int(j)

len_cycle=[] for n in range(201, 210): n_list=[n] while n > 1: if n % 2 == 0: n = n // 2 elif n % 2 != 0 and n != 1: n = 3*n + 1 elif n ==1: break n_list.append(n) len_cycle.append(len(n_list))

print("%d %d %d" %(i, j, max(len_cycle)))

2021/08/19 16:57

김동현

def crp(a,b):
    data = []
    for k in range(a,b+1):
        cl = 1
        while k != 1:
            if k%2 == 0:
                k = k / 2
                cl += 1
            else:
                k = 3*k+1
                cl += 1
        data.append(cl)
    return data

print(max(crp(1,10)))
print(max(crp(100,200)))   
print(max(crp(201,210)))
print(max(crp(900,1000)))

2021/08/21 08:11

한고선

def divide(x) :
    count = 1
    while True:    
        if x == 1 : 
            return count
        elif x % 2 != 0 : 
            count += 1
            x = 3*x +1
        elif x % 2 == 0:
            count += 1
            x /= 2

n = input("").split(" ")
minimum = int(n[0])
maximum = int(n[1])
lengthlist = []
while True :
    lengthlist.append(divide(minimum))
    if minimum == maximum : break
    minimum += 1

print(int(n[0]), int(n[1]), max(lengthlist))

2021/08/24 16:26

//python

def Perd_problem(n):
    list = [n]
    k = 1
    while list[k-1] != 1:
        if n % 2 == 0:
            n = int(n / 2)
            list.append(n)
            k += 1
        elif n % 2 != 0:
            n = int(n * 3 + 1)
            list.append(n)
            k += 1
    return k

a,b = input("두 수를 입력하세요(ex.1 10)>").split(" ")
a = int(a)
b = int(b)
k = []
for i in range(a,b+1):
    k.append(Perd_problem(i))
print(a,b,max(k))

2021/09/02 11:36

박대선

def maxcycle(a,b):
    max=0
    for i in range(a,b+1):
        count=1
        while i !=1:
            if i%2 ==1:
                i= 3*i +1
            else:
                i=i/2
            count+=1
        if max<count:
            max=count
    return max

2021/09/20 18:56

ninanino

def check_odd_even(u):
    if u % 2 == 0: # 짝수라면
        return u/2
    else: # 홀수라면
        return u*3+1

def compute_cycle_length(u):
    a = 1
    while 1:
        if u == 1:
            break
        u = check_odd_even(u)    
        a += 1
    return a    

def compute_cycle_length_two(h,l):
    c = compute_cycle_length(h)
    for s in range(h,l+1):
        if c < compute_cycle_length(s):
            c = compute_cycle_length(s)
    return c


if __name__ == '__main__':
    x,y = map(int, input().split())
    z = compute_cycle_length_two(x,y)

    print("{0}\t{1}\t{2}".format(x,y,z))

2021/09/27 18:04

서현준

import java.util.Scanner;

public class Cd13 {

    public static void main(String[] args) {
        int num1, num2;
        Scanner scanner = new Scanner(System.in);
        num1 = scanner.nextInt();
        num2 = scanner.nextInt();

        int max_generated = 0, max_cycle = 0;
        for(int i = num1; i <= num2; i++) {
            int number = i, cycle = 1;
            while(number != 1) {

                if(number == max_generated) {
                    max_cycle += cycle - 1;
                    max_generated = i;
                    break;
                }

                if(number % 2 == 0) number /= 2;
                else number = number * 3 + 1;
                cycle++;
            }
            if(number == 1 && max_cycle < cycle) {
                max_cycle = cycle;
                max_generated = i;
            }

        }
        scanner.close();
        System.out.println(max_generated + " " + max_cycle);
    }

}

2021/10/24 02:32

YoungJun-Ryu

자바스크립트로 작성하였습니다.

function cycle(i, j) {
  let max = 0
  function calc(number){
    let count = 1
    while(number != 1) {
      number = number%2 == 0 ? number/2 : (number*3) + 1
      count++
      if(max < count) max = count
    }
  }      
  for(let c=i; c<=j; c++) {
    calc(c)
  }  
  console.log(i+" "+j+" "+max)
}

cycle(1, 10)
cycle(100, 200)
cycle(201, 210)
cycle(900, 1000)

2021/11/25 17:55

유정효

def problem(n):
    result =[]
    while True:
        if n ==1:
            result.append(n)
            break 
        elif n % 2 == 0:
            result.append(n)
            n = int(n/2)
        else:
            result.append(n)
            n = int(n*3 +1)
    return result
def do(a,b):
    k = []
    for i in range(a,b+1):
        k.append(len(problem(i)))
    return max(k)

a,b = map(int,input("두 수를 입력하세요:").split())
print(do(a,b))

2021/12/14 15:58

Jun

def sol (num) :
    n = 1
    while num !=1 :
        n +=1
        if num %2 == 0 :
            num /= 2
        else :
            num = num*3 +1
    return n

def solution_max (i,j) :
    a = []
    for k in range(i,j+1) :
        a.append(sol(k))
    return print(max(a))

solution_max(900,1000)

2021/12/20 23:57

양캠부부


def cycle(n,count=1):
    if n == 1 : return count
    n = int(n/2) if n%2 == 0 else (n*3)+1
    count += 1
    return cycle(n,count)

_input = input("숫자 두개 입력 : ")
_input = _input.split()

print( max(list(map(cycle, [num for num in range(int(_input[0]),int(_input[1])+1) ]))) )

2022/01/06 17:53

강태호

def cycle(i, j):
    A = []
    for a in range(i, j+1):
        sum = 1
        while a !=1:
            if a%2 == 0:
                a=a/2
                sum += 1
            else:
                a=a*3+1
                sum += 1
        A.append(sum)
    print(max(A))

2022/01/19 23:33

trim39r

// Rust

// 각 n에 대해 계산하면서 중간 과정에 나오는 숫자들에 대해 사이클 길이를 HashMap에 저장해, 총 계산 수를 줄였습니다.

// 1 ~ 10의 경우 21번 계산,

// 100~200의 경우 430번 계산,

// 201~210의 경우 191번 계산

// 900~1000의 경우 1294번 계산됩니다.

fn main() {

let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("input error");    // /n포함
let mut input = input.trim().split_whitespace();

let i: u32 = input.next().unwrap().parse().expect("Parse error");
let j: u32 = input.next().unwrap().parse().expect("Parse error");

println!("{} {} {}", i, j, cycle_length(i, j));

}

use std::collections::HashMap; fn cycle_length(i: u32, j: u32) -> usize {

let mut map: HashMap<u32, usize> = HashMap::new();
map.insert(0, 0);
let mut max_len = 0;
let mut count = 0;

for n in i..=j {
    let mut vec = vec![n];
    let mut len = 1;
    let mut m = n;

    while m > 1 {
        if map.contains_key(&m) {
            len += map[&m] - 1;
            for _ in 1..map[&m] {
                vec.push(0);
            }
            break;
        }

        count += 1;
        if m % 2 == 0 {
            m /= 2;
        } else {
            m = 3 * m + 1;
        }
        vec.push(m);
        len += 1;
    }

    for k in 0..(vec.len()-1) {             // 마지막 1 제외
        if !map.contains_key(&vec[k]) {
            map.insert(vec[k], vec[k..].len());
        }
    }
    max_len = max_len.max(len);
}
println!("count: {}", count);
max_len

}

2022/01/27 00:32

JW KIM

def cycle(n):
    seq = [n]
    while n != 1:
        if n%2 == 0:
            n = n/2
            seq.append(n)

        else:
            n = n*3 + 1
            seq.append(n)

    return len(seq)

m,n = map(int, input('두 숫자를 입력하세요.(space bar 분리)').split(' '))

print(max([cycle(x) for x in range(min(m,n),1+max(m,n))]))

2022/02/07 20:01

로만가

package org.javaturotials.ex;
import java.util.*;


public class test {
    public static void main(String[] args) {
    Scanner sc =  new Scanner(System.in);
    int x = sc.nextInt();
    int y = sc.nextInt();
    int max=0;
    int count=0;
    for(int i=x; i<=y; i++) {
    int ox=i;
    while(true) {
        if(ox%2==0) {
            ox=ox/2;
        }
        else if(ox%2!=0) {
            ox=(ox*3)+1;
        }
        count++;
        if(ox==1) break;
    }
    if(count>max) max=count+1;
    count=0;
    }
    System.out.print(max);
    }
    }

2022/02/18 12:36

Kkubuck

i, j = map(int,input("i, j? ").split())

def check(n):
    li = [n,]
    while n != 1:
        if n % 2 == 0:
            n = n / 2
            li.append(n)
        else:
            n = n*3 + 1
            li.append(n)
    return len(li)
result = check(i)
for n in range(i,j+1):
    if check(n) > result:
        result = check(n)

print(f"i: {i} j: {j} 최대사이클: {result}")

2022/02/21 17:16

김정원

def seq_len(a):
    seq=[]
    seq.append(a)
    while seq[-1]!=1:
        if seq[-1]%2==0:
            seq.append(seq[-1]//2)
        else:
            seq.append(seq[-1]*3+1)
    return len(seq)

i=input('처음숫자 ')
j=input('마지막숫자 ')
a=[]
for x in range(int(i),int(j)+1):
    a.append(seq_len(x))
print(max(a))

2022/03/03 18:56

코딩초보박영규

def cy_len (x):
    y = [x]
    while y[-1] != 1:
        if y[-1] % 2 == 0: y += [y[-1] / 2]
        else: y += [y[-1] * 3 + 1]
    return len(y)

def maxcy_len(i,j):
    maxcy = []
    for x in range(i,j): maxcy += [cy_len(x)]
    return max(maxcy)

exam_input = [[1,10],[100,200],[201,210],[900,1000]]
for i in range(len(exam_input)): 
    print(exam_input[i][0], exam_input[i][1], maxcy_len(exam_input[i][0],exam_input[i][1]))

2022/03/17 11:03

엄태용

def threeproblem(m, n):
    lst = []
    for i in range(m, n+1):
        count = 1
        while i > 1:
            count += 1
            if i % 2 == 0:
                i /= 2
            else:
                i = i * 3 + 1
        lst.append(count)
    print(max(lst))
threeproblem(100, 200) # 125

2022/03/19 22:56

kh ahn

def cypro(k):
    cl=1
    while k != 1:
        if k%2==0:
            k=k/2
            cl+=1
        else:
            k=3*k+1
            cl+=1
    return cl

i=int(input('INPUT MIN NUM : '))
j=int(input('INPUT MAX NUM : '))
t=0
arw=[]

for t in range(i,j+1):
    arw.append(cypro(t))
print(max(arw))

2022/04/02 11:32

DongWoo

# 사이클 길이를 구하는 함수
def FindCycleLength(n):
    nList = []              # 수열 저장을 위한 빈 리스트 생성
    while n != 1:           # n = 1 이 될 때까지 반복
        if n % 2 == 0:      # 쩍수 일 경우 2로 나누어 리스트에 저장
            n /= 2
            nList.append(n)
        else:               # 홀수 일 경우 3을 곱해서 1을 더한 값 저장
            n = 3*n + 1
            nList.append(n)
    nList.append(n)         # 마지막 n=1 일 때 n값 저장
    return len(nList)

# 2개의 정수 사이의 모든 수의 최대 싸이클 길이 구하는 함수
def FindMaxCycleLength():
    a, b = map(int, input("두개의 정수를 입력하세요: ").split())    # 2개의 정수를 입력
    cycleLenList = []          # 사이클 길리을 저장하는 빈 리스트 생성
    for num in range(a, b+1):      # 두 정수를 포함한 사이값을 순회
        cycleLenList.append(FindCycleLength(num))    # FindCycleLength()를 호출하여 사이클 길이를 리스트에 저장
    return max(cycleLenList)     # 리스트 중 가장 큰 값을 반환
FindMaxCycleLength()

2022/04/11 23:47

Charles

def num(n,m): li1=[] for i in range(n,m+1): li = [] while i>1: if i%2==0: i=i/2 else: i=i*3+1 li.append(int(i)) count=len(li)+1 li1.append(count) return(max(li1)) print(num(201,210))

2022/04/14 16:09

yunjae

자바로 풀어봤습니다.

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("자연수 M, N을 입력하시오:");
        int M = scan.nextInt();
        int N = scan.nextInt();
        int maxCount=0, count=1, copy;

        for(int i=M; i<=N; i++) {
            copy = i;
            while(copy!=1) {
                if(copy%2==0) {
                    copy/=2;
                    count++;
                }else {
                    copy = (copy*3)+1;
                    count++;
                }
            }

            if(count>maxCount) {
                maxCount = count;
            }

            count=1;
        }

        System.out.printf("%d ~ %d 사이의 모든 수에 대한 최대 사이클 길이는 %d이다.\n", M, N, maxCount);
    }
}

2022/06/09 03:36

유로

x = int(input("min : "))
y = int(input("max : "))

def Problem(n):
    n_list = [n]
    while n != 1:
        if n % 2 == 0:
            n = n / 2
            n_list.append(n)
        else:
            n = n * 3 + 1
            n_list.append(n)
    return len(n_list)

result = max([Problem(x) for x in range(x,y+1)])
print("result :",result)

2022/06/18 11:21

김시영

파이썬으로 작성하였습니다.

class problem:
    def __init__(self, i, j):
        self.i = i
        self.j = j

    def cycle(self):
        result = []
        p=0
        dic={}

        for n in range(self.i, self.j+1):
            result.clear()
            result.append(n)
            while n > 1:
                if n % 2 == 0:
                    n = n // 2
                    result.append(n)
                elif n == 1:
                    result.append(1)
                elif n % 2 != 0:
                    n = 3 * n + 1
                    result.append(n)
            dic['{0}'.format(self.i+p)]=len(result)
            p+=1
        return dic

    def solve(self):
        value_list =problem.cycle(self).values()
        ans = max(value_list)
        a = ",".join([k for k, v in problem.cycle(self).items() if v == ans])
        print("최대 사이클 길이 : {0}\n그때의 수: {1}".format(ans,a))

i=int(input('INPUT MIN NUM: '))
j = int(input('INPUT MAX NUM: '))

a= problem(i,j)
a.solve()

2022/06/19 23:09

gyachom

cmd_i = int(input("정수 i를 입력하시오 :"))               #i, j의 값을 입력받음
cmd_j = int(input("정수 i보다 큰 정수 j를 입력하시오 :"))

num_range = range(cmd_i, cmd_j + 1)                #i, j사이의 숫자 범위 형서

cycle_list = []                                     #싸이클을 구한 후 리스트에 저장해서 나중에 비교

for n in num_range:                                 #i, j 사이의 사이클 구하기
    num_list = []
    while n != 1:
        num_list.append(n)

        if n % 2 == 0:
            num = n/2
            n = num

        else:
            num = n*3 +1
            n = num

    cycle_list.append(len(num_list)+1)                #구한 사이클 길이 저장

print(f"{cmd_i} {cmd_j} {max(cycle_list)}")         #구한 값 프린트

2022/08/12 19:39

박종훈

a=input("원하는 숫자 범위를 입력하세요(띄어쓰기로 구분):")
a=a.split()
a_int=[int(i) for i in a]
#a_int_last=a_int[-1]
a_list=[int(b) for b in range(a_int[0],a_int[1])]
a_list.append(a_int[-1])
result=[]
for n in range(0,len(a_list)):
    k=a_list[n]
    result_tem=[k]
    if k==1:
        k=k*3+1
        result_tem.append(k)
    while k!=1:
          if k%2==0:
             k=int(k/2)
             result_tem.append(k)
          else:
             k=int(k*3+1)
             result_tem.append(k)
    result_tem_len=len(result_tem)
    result.append(result_tem_len)
result_max=max(result)       
print(result_max)    

2022/08/22 00:37

나무늘보

i,j = map(int,input().split(" "))
a = []
for k in range(i,j+1):
    c=1
    while k > 1:
        if k%2==0:
            k/=2
            c+=1
        else:
            k*=3
            k+=1
            c+=1
    print(c)
    a.append(c)

print(max(a))

2022/08/25 03:18

허명재

a,b = map(int, input().split())
max_count = 0
for i in range(a,b):
    count = 1
    while i!=1:
        if i%2 == 0:
            i /= 2
        else:
            i = i*3 +1
        count +=1
    if max_count < count:
        max_count=count
print(a,b,max_count)

2022/09/06 22:08

준표장

# 3n+1 Problem

def n(x,y):
    a=[]    
    for i in range(x,y+1):
        count = 1
        while i != 1:
            if i%2 == 0:
                i = i / 2
                count += 1
            elif i%2 == 1:
                i = (i * 3) + 1
                count += 1
        a.append(count)
    print(x,y,max(a))

n(1,10)
n(100,200)
n(201,210)    
n(900,1000)

2022/09/13 15:06

어필힝

Python 3.11 버전입니다
def MaxCycleLength(i,j):
    a = []
    for k in range(i,j+1):
        x = 1
        while k != 1:
            if k % 2 == 0:
                k = k/2
            else:
                k = k*3 + 1
            x += 1
        a.append(x)
    return max(a)


2022/11/01 12:52

이웅기

# 3n+1 problem

i = int(input("1st number: "))
j = int(input("2nd number: "))

list = []

for n in range(i,j):
    count = 0
    if n == 1:
        n = int(n*3 + 1)
    while not n == 1:
        if n % 2 == 0:
            n = int(n / 2)
            count+=1
        else:
            n = int(n*3 + 1)
            count+=1
    list.append(count)

print(max(list)+1)

2022/11/10 21:04

­류예린

num1 = int(input("숫자1 : "))
num2 = int(input("숫자2 : "))

count_list = [] # 카운트를 저장할 리스트
for i in range(num1, num2 + 1) :
    count = 1
    while i != 1 :
        if i % 2 == 0 :
            i = i / 2
        else :
            i = i * 3 + 1
        count += 1
    count_list.append(count)
print("최대 사이클 :",  max(count_list))
print("최대 사이클을 가지는 수 :", count_list.index(max(count_list)) + num1)

2022/11/17 14:27

ㅇㅇ

Python. 에러 없이 한 번에 짰다는 게 뿌듯하긴 한데, 역시 코드를 좀 더 짧게 만드는 능력을 키워야 할 것 같습니다. '두 수 사이의 수'를 설정하는 것이 가장 어려운 부분이었습니다.

def cycle_length(number): #사이클 길이를 만드는 함수
    sequence = []
    result = 0
    while number != 1:
        sequence.append(number)
        if number % 2 == 0:
                number = number // 2
        elif number % 2 == 1:
                number = number * 3 + 1
    sequence.append(number)
    result = len(sequence)
    return result

def max_cycle_length(i, j): #두 수 사이의 수에 대하여 최대 사이클 길이를 구하는 함수
    temp = 0
    if j > i: #반드시 작은 수에서 큰 수 순으로 입력되는 것이 아니므로 두 가지 경우로 구분하여 함수 설정
        while i != j+1: #j까지 포함해야 하므로 while문의 종료 시점은 i가 j+1이 되었을 때로 설정
            a = cycle_length(i)
            if a > temp: #최대 사이클 길이를 구하기 위한 비교
                temp = a
            i += 1
    elif i > j:
        while j != i+1:
            a = cycle_length(j)
            if a > temp:
                temp = a
            j += 1
    return temp

print(max_cycle_length(900, 1000))

2022/12/01 17:34

Frye 'de Bacon

i, j = map(int, input().split())
for k in range(i, j+1):
    L1=[]; L1.append(k);
    while k != 1:
        if k%2==0:
            k//=2
            L1.append(k)
        else:
            k*=3
            k+=1
            L1.append(k)
    L2.append(len(L1))
print(i, j, max(L2))

2023/01/27 20:49

김민주

JAVA

package chapter03; import java.util.Scanner;

public class UnproofedMatter { public static void main(String[] args) { Scanner scn = new Scanner(System.in);

    int i, j, temp=0;

    System.out.print("정수 2개를 입력>>");
    i = scn.nextInt();
    j = scn.nextInt();

    for (int k = i; k <= j ; k++) {
        int n=k;
        int count = 1;
        while (n>1) {
            if (n%2==0) {
                n /=2;

            } else {
                n = n*3 +1;
            }
            count++;
        }
        if (count>temp) {
            temp = count;
        }
    }
    System.out.println(temp);
}

}

2023/03/17 17:47

Do Il Yoon

a, b = 900, 1000
result = 0

for n in range(a, b+1):
    cycle = 1

    while True:
        n = n / 2 if n % 2 == 0 else n * 3 + 1
        cycle += 1
        result = cycle if cycle > result else result

        if n == 1:
            break

print(result)

>>> 174

무식하게 풀었지만 답은 제대로 나오는 것 같아요.

2023/03/26 15:18

관산정

def cycle(n):
    lst = []
    while n != 1:
        lst.append(n)
        if n % 2 == 0:
            n //= 2
        elif n % 2 != 0:
            n = n * 3 + 1
    lst.append(1)
    return len(lst)



def npro():
    usr = [int(e) for e in input().split()]

    m = cycle(usr[0])

    for i in range(usr[0] + 1, usr[1] + 1):
        if cycle(i) > m:
            m = cycle(i)

    print(m)

npro() 

2023/04/21 16:37

장지훈

a = int(input("A:"))
b = int(input("B:"))
max_ = [];li = []
x = tcyc = 0

while a+x <= b:
   li.append(a+x)
   x += 1

def find_tcyc(n):
   tcyc = 0
   while n > 1:
      tcyc += 1
      if n % 2 == 0:
         n /= 2
      else:
         n = n * 3 + 1
   return tcyc

for i in li:
   y = find_tcyc(i)
   max_.append(y)

print(a,'\t',b,'\t',max(max_))

2023/09/07 10:05

siu yoon

def cycle(a,b):
    maxCycle = 1
    for num in range(a, b+1):
        curr = 1
        while num != 1:
            if num % 2 == 0:
                num //= 2
            else:
                num = 3*num + 1
            curr += 1
        maxCycle = max(maxCycle, curr)
    return maxCycle

def split_p(P):
    w = []
    curr = ''
    for p in P:
        if p==' ':
            if curr != '':
                w.append(int(curr))
                curr = ''
        else:
            curr += p
    if curr != '':
        w.append(int(curr))
    return w


inp = """1    10
100  200
201  210
900  1000"""

inp_split = inp.split('\n')
for P in inp_split:
    p_split = split_p(P)
    print(P, "%5d" %( cycle(int(p_split[0]), int(p_split[1]))))

2024/02/03 13:27

insperChoi

JAVA입니다.

package three_n_plus_one_problem;

import java.util.Scanner;

public class CycleCounter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        int j = sc.nextInt();

        int maxCycle = -1;

        for (int k = i; k <= j; k++) {
            int result = getCycle(k);
            if(result > maxCycle) {
                maxCycle = result;
            }
        }
        System.out.println(maxCycle);
    }

    static int getCycle(int num, int cycle) {
        cycle = cycle + 1;
        int result;
        if(num % 2 == 0) {
            result = num / 2;
        }
        else {
            result = num * 3 + 1;
        }

        if(result != 1) {
            return getCycle(result, cycle);
        }
        else {
            return cycle;
        }
    }
    static int getCycle(int num) {
        return getCycle(num, 1);
    }
}

2025/01/22 23:20

박준우

def ruleCycle(a):
  cycleCnt = 1
  while a != 1:
   if a % 2 == 0:
     a = a/2
     cycleCnt += 1
   else:
     a = (a*3) + 1
     cycleCnt += 1
  return cycleCnt

minNum = int(input("Input min number: "))
maxNum = int(input("input max number: "))

cycleNum = []

for i in range(minNum, maxNum+1):
  cycleNum.append(ruleCycle(i))

print(max(cycleNum))

2025/02/21 20:29

Dasol Lee

list_i_j=list()
list_int_i_j=list()
while True:
    i_j=input().split()
    if len(i_j)==1:
        break
    if len(i_j)>2:
        break
    if len(i_j)==0:
        break
    list_i_j.append(i_j)
list_max_cycle=list()
for a in range(len(list_i_j)):
    list_int_i_j.append(tuple(map(int,list_i_j[a])))
print(list_int_i_j)
for a in range(len(list_int_i_j)):
    start,end=list_int_i_j[a]
    print('start:',start,'end:',end)
    list_cycle=list()
    max_cycle=0
    for n in range(start,end+1):
        list_cycle.append(n)
        while True:
            if n%2==0:
                n//=2
                list_cycle.append(n)
            else:
                n=(n*3)+1
                list_cycle.append(n)
            if n==1:
                break
        print(list_cycle)
        if max_cycle<len(list_cycle):
            max_cycle=len(list_cycle)
        list_cycle.clear()
    list_max_cycle.append(max_cycle)
    print(list_max_cycle)
for a in range(len(list_max_cycle)):
        start,end=list_int_i_j[a]
        print('{} {} {}'.format(start,end,list_max_cycle[a]))

2025/04/22 19:34

박성우

목록으로