본문 바로가기

Algorithm/Implementation

(C++, Rust) - 백준(BOJ) 13236 : Collatz Conjecture

반응형

https://www.acmicpc.net/problem/13236

 

13236번: Collatz Conjecture

The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first proposed it in 1937 and is still an open problem in mathematics.  The sequence of numbers involved is referred to as the hailstone sequence or hailstone numbers (b

www.acmicpc.net

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

초기 숫자 n을 선언해 줍니다.

📔 풀이과정

조건에 따라 n이 양수인 동안 while loop를 수행하며 계산을 수행합니다.

📔 정답출력

형식에 맞게 n을 출력합니다.


📕 Code

📔 C++

#include <bits/stdc++.h>
using namespace std;
int n;
int main(){ 
  cin >> n;
  cout << n << ' ';
  while(n > 1) {
    if(n % 2) n = n * 3 + 1;
    else n /= 2;
    cout << n << ' ';
  }
}

📔 Rust

use std::io;

fn main(){
  let mut line = String::new();
  io::stdin().read_line(&mut line).expect("wrong io");
  let mut n = line.trim().parse::<i64>().unwrap();
  print!("{} ", n);
  while n > 1 {
    if n % 2 > 0 {
      n = n * 3 + 1;
    }
    else {
      n = n / 2;
    }
    print!("{} ", n);
  }
}

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.