c++ - 不使用循环和数字和的数字根递归

标签 c++ recursion function-definition

我正在尝试解决下面这个递归问题,它显然要求在不使用循环或数字和的情况下找到 digitaroot。这可能吗?

{整数 n 的数字根定义为对数字重复求和直到只剩下一个数字的结果。比如1729的数字根 可以使用以下步骤计算: 第 1 步:1 + 7 + 2 + 9 → 19 第 2 步:1 + 9 → 10 第 3 步:1 + 0 →

因为第3步最后的合计是个位数1,所以那个值就是数字 根。 写一个函数 DigitalRoot(n) 返回其参数的数字根。 尽管使用 DigitalSum 函数很容易实现 DigitalRoot 练习 6 和一个 while 循环,这个问题的部分挑战是在不使用任何显式循环结构的情况下递归地编写函数。

最佳答案

接住!:)

#include <iostream>

unsigned int digital_root( unsigned int x )
{
    if ( x < 10 ) return x;

    x = x % 10 + digital_root( x / 10 );

    return x < 10 ? x : digital_root( x ); 
}

int main(void) 
{
    std::cout << digital_root( 1729 ) << std::endl;
    std::cout << digital_root( 1917 ) << std::endl;

    return 0;
}

程序输出为

1
9

或者你可以将函数的返回语句改写成下面的方式

unsigned int digital_root( unsigned int x )
{
    if ( x < 10 ) return x;

    x = x % 10 + digital_root( x / 10 );

    return digital_root( x ); 
}

或者函数看起来像这样

unsigned int digital_root( unsigned int x )
{
    return x < 10 ? x : digital_root( x % 10 + digital_root( x / 10 ) ); 
}

关于c++ - 不使用循环和数字和的数字根递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484134/

相关文章:

c++ - 从基类成员函数返回派生类的实例

C++ 将共享库中的导出定义用作内联

c++ - 比较从递归树分支返回的 vector

c++ - 无法将 const_iterator 绑定(bind)到 const_iterator

java - 了解二叉搜索树计数

c - 在程序中出现不兼容的整数到指针的转换错误。不确定这是如何/为什么会发生,但正在寻找解释

c++ - 从网络服务器传输套接字文件

c++ - 如何从图像中提取 FAST 特征?

haskell - 在 Haskell 中查找组合函数的类型

c++ - 矩阵每行中的最小元素 C++