cses

CSES Solutions (0x6A73)
git clone https://git.pngu.org/cses
Log | Files | Refs

commit be030b74805f245c8618c77b03e76f16b3fc945a
Author: Jack Sangdahl <jack@pngu.org>
Date:   Tue, 17 Dec 2024 13:18:18 -0700

1608. weird algorithm

Diffstat:
A.gitignore | 1+
Aintroductory_problems/readme.md | 8++++++++
Aintroductory_problems/weird_algorithm.cpp | 13+++++++++++++
3 files changed, 22 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1 @@ +*.out diff --git a/introductory_problems/readme.md b/introductory_problems/readme.md @@ -0,0 +1,8 @@ +## Introductory Problems + +### Weird Algorithm +Consider an algorithm that takes as input a positive integer `n`. If `n` is even, the algorithm divides it by two, and if `n` is odd, the algorithm multiplies it by three and adds one. The algorithm repeats this, until `n` is one. Your task is to simulate the execution of the algorithm for a given value of `n`. + +**Input**: The only input line contains an integer `n`. (Example: 3) + +**Output**: Print a line that contains all values of `n` during the algorithm. (Example: 3 10 5 16 8 4 2 1) diff --git a/introductory_problems/weird_algorithm.cpp b/introductory_problems/weird_algorithm.cpp @@ -0,0 +1,13 @@ +// 1608. Weird Algorithm +#include <bits/stdc++.h> +using namespace std; + +int main() { + long long num; + scanf("%lld", &num); + while (num > 1) { + printf("%lld ", num); + num = num & 1 ? 3 * num + 1 : num / 2; + } + printf("1\n"); +}