使用递归乘以数字的数字

时间:2014-11-12 15:29:43

标签: c recursion

我正在做以下练习:

  

给出一个四位数字,例如3183,将每个数字与最后一个数字进行比较,如果大于或等于,则将其与下面的数字进行比较

示例:对于数字3183,它将是n = 3*8*3 = 72

我的代码:

#include <stdio.h>

int f ( int n )
{
    if ( n < 10 ) 
      return n ;
    return (((n/10) % 10) >= (n%10) ? ((n/10)10) : 1) * f((n/100 )* 10 + n % 10 ) ;
}

int main() 
{
    printf( "%d", f( 3183 );

    return(0);
}

有没有办法缩短或改善它?

4 个答案:

答案 0 :(得分:3)

让另一种方法比原来更紧凑:

#include <stdio.h>

int f (int n, int u)
{
    if (u > n) return(1);
    return (n % 10 >= u ? n % 10 : 1) * f(n/10, u);
}

int main (void)
{
    int n = 3284;
    printf ("%d", f (n , n%10));

    return(0);
}

答案 1 :(得分:1)

编辑我昨天误读了这个。现在没有必要有效地重新创建@Red Alert的答案,但我无法删除它,因为它已被接受,所以这里就是这样。

我认为我们可以创造自己的内心&#34;维持状态的功能。我还假设数字是从右边处理的,原始的例子是不清楚的。

static int g(int n, int ack, int last)
{
  const int here = n % 10;
  const bool mult = here >= last;

  if(n < 10)
    return mult ? here * ack : here;
  return g(n / 10, mult ? here * ack : ack, here);
}

int f(int n)
{
  return g(n, 1, 0);
}

答案 2 :(得分:0)

接受回答后

OP的代码无法编译,缺少%

//     (((n/10) % 10) >= (n%10) ? ((n/10) 10) : 1) * f((n/100 )* 10 + n % 10 ) ;
return (((n/10) % 10) >= (n%10) ? ((n/10)%10) : 1) * f((n/100 )* 10 + n % 10 ) ;

正如@interjay建议的那样,保存结果而不是重新计算。

#include <stdio.h>

int f(int n) {
  if (n < 10)
    return n;
  int lastdigit = n % 10;
  int nextlastdigit = (n / 10) % 10;
  return (nextlastdigit >= lastdigit ? nextlastdigit : 1)
      * f((n / 100) * 10 + lastdigit);
}

int main(void)   {
    printf( "%u", f(2183); // --> 24
    return(0);
}

为了使更好,我会减少除法调用和乘以1.但更好在这一点上是主观的。

unsigned cheroky(unsigned x) {
  if (x < 10)
    return x;
  unsigned lastdigit = x % 10;
  unsigned firstdigits = x / 10;
  unsigned lastfirstdigit = firstdigits % 10;
  unsigned nextx = firstdigits - lastfirstdigit + lastdigit;
  unsigned product = cheroky(nextx);
  if (lastfirstdigit >= lastdigit)
    product *= lastfirstdigit;
  return product;
}

要真正改进,会使用非递归循环。

unsigned cheroky2(unsigned x) {
  unsigned lastdigit = x % 10;
  unsigned product = lastdigit;
  while (x >= 10) {
    x /= 10;
    unsigned nextdigit = x % 10;
    if (nextdigit >= lastdigit)
      product *= nextdigit;
  }
  return product;
}

答案 3 :(得分:0)

您是否可以使用中间递归函数?这消除了您为保持最后一位数字状态所做的额外数学运算:

int f2 ( int n, int lastDigit )
{
    int currentDigit = n%10;
    int returnDigit = currentDigit;
    if(currentDigit < lastDigit)
        returnDigit = 1;
    if(n < 10)
        return returnDigit;

    return returnDigit * f2(n/10, lastDigit );
}

int f ( int n )
{
    if ( n < 10 ) 
      return n ;
    return n%10* f2(n/10, n%10);
}
相关问题