首页 > 其他 > 详细

SGU118 数学题 Math

时间:2014-01-31 15:15:49      阅读:428      评论:0      收藏:0      [点我收藏+]

问题:令f(n)为n各个位数字之和。n的Digital Root是f(f(...f(n))),是一位数字。现在给你A1,A2...An,n个数,求A1*A2*…*AN + A1*A2*…*AN-1 + … + A1*A2 + A1的Digitial Root。

Problem: Let f(n) be a sum of digits for positive integer n. If f(n) is one-digit number then it is a digital root for n and otherwise digital root of n is equal to digital root of f(n). For example, digital root of 987 is 6. Your task is to find digital root for expression A1*A2*…*AN + A1*A2*…*AN-1 + … + A1*A2 + A1.

解法:首先明确DR(A + B) = DR(DR(A) + DR(B)),继续推导有DR(A * B) = DR(DR(A) * DR(B))。

设S1 = A1*A2*…*AN + A1*A2*…*AN-1 + … + A1*A2 + A1,

DR(S1)

= DR(A1 + A1 * S2)

= DR(DR(A1) + DR(DR(A1)*DR(S2)))

= DR(DR(A1) + DR(DR(A1)*DR(A2 + A2*S3)))

= DR(DR(A1) + DR(DR(A1)*DR(A2)) + DR(DR(A1)*DR(A2)*DR(S3)))

=DR(Sum(DR(A1)*...*DR(Ai))) (i=1-->N)

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int a[1010],cas,n,ans,tt;
int f(int x) {
    if (x<10) return x;
    int sum = 0;
    while (x) {
          sum += x%10;
          x /= 10;
    }
    return f(sum);
}
int main() {
    scanf("%d",&cas);
    while (cas--) {
          scanf("%d",&n);
          for (int i=1;i<=n;i++)
              scanf("%d",&a[i]);
          ans = tt = f(a[1]);
          for (int i=2;i<=n;i++) {
              tt = f(tt*f(a[i]));
              ans += tt;
          }
          printf("%d\n",f(ans));
    }
    return 0;
}


SGU118 数学题 Math

原文:http://blog.csdn.net/lotus_land/article/details/18883529

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!