SGU - 118 Digital Root

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.

Input

Input file consists of few test cases. There is K (1<=K<=5) in the first line of input. Each test case is a line. Positive integer number N is written on the first place of test case (N<=1000). After it there are N positive integer numbers (sequence A). Each of this numbers is non-negative and not more than 109.

Output

Write one line for every test case. On each line write digital root for given expression.

Sample Input

1
3 2 3 4

Sample Output

5

数根公式这里写图片描述
又因为(x*y)%9 = (x%9)*(y%9)
所以可以推得答案

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;

#define ll long long

int main(){
    int n, k;
    int a;
    int s;
    int s1;
    scanf("%d", &n);
    while(n--){
        int i, j;
        s=0;
        s1 = 1;
        scanf("%d", &k);
        for(i = 0; i < k; i++){
            scanf("%d", &a);
            a = a%9;
            s1=s1*a%9;
            s = (s+s1)%9;
        //cout << s << endl;

        }
        if(s!=0)
        printf("%d\n", s);
        else
            printf("9\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ling_wang/article/details/80572105
sgu
118
今日推荐