實現科拉茨猜想
在本教程中,我們將討論一個實現科拉茨猜想的程式。
為此,我們將獲得一個數字 n,並且我們必須找出是否可以使用兩種操作將它轉換為 1 −
如果 n 是偶數,則 n 轉換為 n/2。
如果 n 是奇數,則 n 轉換為 3*n + 1。
示例
#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; }
輸出
Yes
廣告