- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to implement Collatz Conjecture
In this tutorial, we will be discussing a program to implement Collatz Conjecture.
For this, we will be given with a number n and we have to find out whether it can be converted to 1 using two operations −
If n is even, n is converted to n/2.
If n is odd, n is converted to 3*n + 1.
Example
#include<bits/stdc++.h> using namespace std; //checking if n reaches to 1 or not bool check1(int n, unordered_set<int> &s){ if (n == 1) return true; if (s.find(n) != s.end()) return false; return (n % 2)? check1(3*n + 1, s) : check1(n/2, s); } bool if_one(int n){ unordered_set<int> s; return check1(n, s); } int main(){ int n = 234; if_one(n) ? cout << "Yes" : cout <<"No"; return 0; }
Output
Yes
Advertisements