zoukankan      html  css  js  c++  java
  • SGU[118] Digital Root

    Description

    描述

    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.

    令f(n)表示正整数n的各个位上数字之和。如果f(n)是一个一位数,那么则是n的一个数字根,否i则,n的数字根等于f(n)的数字根。例如987的数字根为6。你的任务是求表达式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.

    输入包含多组测试数据。输入的第一行为K (1 <= K <= 5),表示测试数据组数。

    每组测试数据占一行,第一个整数N (N <= 1000)表示Ai的个数,接下来N个数表示Ai,保证Ai非负且不超过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

     

    Analysis

    分析

    结论题——f(n) ≡ n(mod 9)。

    证明如下:

    令n = a0 * 10p0 +  a1 * 10p1 + ... + am-1 * 101 + am * 100,其中n为m位数。

    则n mod 9 = a0 + a1 + ... + am-1 + a= f(n),即f(n) ≡ n(mod 9)。

    证毕。

    需要注意的是,当n mod 9 == 0的时候,f(n) = 9。

    读入的时候要先把数据mod 9,否则中间计算过程会超int。

     

    Solution

    解决方案

    #include <iostream>
    
    using namespace std;
    
    const int MAX = 1024;
    
    int pData[MAX];
    
    int main()
    {
    	int T, N;
    	cin >> T;
    	for(int i = 1; i <= T; i++)
    	{
    		int ans = 0;
    		cin >> N;
    		for(int j = 1; j <= N; j++)
    		{ cin >> pData[j]; pData[j] %= 9; }
    		for(int j = 1; j <= N; j++)
    		{
    			int nTmp = 1;
    			for(int k = 1; k <= j; k++)
    			{
    				nTmp *= pData[k];
    				if(nTmp >= 9) { nTmp %= 9; }
    			}
    			ans += nTmp;
    			if(ans >= 9) { ans %= 9; }
    		}
    		cout << (ans == 0 ? 9 : ans) << endl;
    	}
    }
    

      

    又是一个数论结论,结论题有时候还是挺难想到的。

  • 相关阅读:
    并行逻辑回归
    【math】梯度下降法(梯度下降法,牛顿法,高斯牛顿法,Levenberg-Marquardt算法)
    MATLAB 按条件进行加和
    MATLAB 统计不同区间中元素的个数
    MATLAB 统计元素出现的次数
    MATLAB 程序处理结果出现 NAN 问题
    Debug 路漫漫-07
    MATLAB 程序计算结果出现 复数(a+bi)问题
    关于安装 Microsoft Office
    关于推荐系统中的长尾商品
  • 原文地址:https://www.cnblogs.com/Ivy-End/p/4298714.html
Copyright © 2011-2022 走看看