不使用循环和数字的数字根复发

时间:2015-05-27 13:36:23

标签: c++ recursion

Iam试图解决下面的这个递归问题,显然是要求在不使用循环或digitum的情况下找到digitaroot。这是可能的吗?

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

因为步骤3结尾处的总数是单个数字1,所以该值是数字的 根。 写一个函数 DigitalRoot(n)返回其参数的数字根。 虽然使用DigitSum函数很容易实现DigitalRoot 练习6和while循环,这个问题的部分挑战是递归地编写函数而不使用任何显式循环结构。}

3 个答案:

答案 0 :(得分:1)

抓住:!)

#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

或者您可以通过以下方式重写函数的return语句

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 ) ); 
}

答案 1 :(得分:0)

我认为你应该首先拆分数字(取n%10和n / 10,然后在第二面应用递归。

然后将问题应用于结果。编写递归函数的关键是记住只有当传入参数为&lt;时才必须返回(没有子调用)。 10。

答案 2 :(得分:-1)

也许你可以从python重做代码:这在几个测试用例上起作用

INDIRECT()