Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

角谷猜想c++语言

作者:黑白灰调   发布日期:2026-07-29   浏览:26

#include <iostream>
using namespace std;

// 角谷猜想(Collatz Conjecture)函数
void collatzConjecture(int n) {
    int steps = 0;
    cout << "Sequence starting from " << n << ": ";

    while (n != 1) {
        cout << n << " ";
        // 如果 n 是偶数,则除以 2
        if (n % 2 == 0) {
            n = n / 2;
        } 
        // 如果 n 是奇数,则乘以 3 加 1
        else {
            n = 3 * n + 1;
        }
        steps++;
    }
    cout << n << endl;  // 最后输出 1
    cout << "Total steps: " << steps << endl;
}

int main() {
    int number;
    cout << "Enter a positive integer: ";
    cin >> number;

    if (number <= 0) {
        cout << "Please enter a positive integer." << endl;
        return 1;
    }

    collatzConjecture(number);
    return 0;
}

解释说明:

  1. collatzConjecture 函数:该函数接收一个整数 n,并根据角谷猜想的规则进行操作,直到 n 变为 1。每次操作都会打印当前的 n 值,并记录步数。

    • 如果 n 是偶数,则将其除以 2。
    • 如果 n 是奇数,则将其乘以 3 并加 1。
  2. main 函数:程序从这里开始执行,提示用户输入一个正整数,并调用 collatzConjecture 函数来展示角谷猜想的过程。

  3. 输入验证:如果用户输入的不是正整数,程序会提示重新输入。

  4. 输出:程序会输出从输入的整数到 1 的整个序列,并统计总共需要多少步。

上一篇:c++list

下一篇:c++ strstr

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++字符串切片

c++ functional

嵌入式c++

c++框架代码

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站