CodeForces - 10C Digital Root【数论】

【题目描述】
Not long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x is the sum s(x) of all the digits of this number, if s(x) ≤ 9, otherwise it is d(s(x)). For example, a digital root of the number 6543 is calculated as follows: d(6543) = d(6 + 5 + 4 + 3) = d(18) = 9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors’ digital roots, i.e. d(xy) = d(d(x)d(y)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That’s why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.

【输入】
The first line contains the only number N (1 ≤ N ≤ 106).

【输出】
Output one number — the amount of required A, B and C from the range [1, N].

【样例输入1】
4

【样例输出1】
2

【样例输入2】
5

【样例输出2】
6

题目链接:https://codeforces.com/contest/10/problem/C

需要先推出一个结论,某谷有dalao证明
d ( x ) = { x m o d 9 (x mod 9!=0) 9 (x mod 9 =0) d(x)= \begin{cases} & x & mod & 9 & \text{(x mod 9!=0)}\\ & 9 & & & \text{(x mod 9 =0)} \end{cases} d(x)={ x9mod9(x mod 9!=0)(x mod 9 =0)

枚举所有d(d(A)d(B))=d(C))的情况,再减去所有AB=C的情况
会爆int,要开long long

代码如下:

#include 
using namespace std;
typedef long long ll;
ll res;
int cnt[10];
int n;
int d(int x)
{
     
    if(x%9) return x%9;
    return 9;
}
int main()
{
     
    cin>>n;
    for(int i=1;i<=n;i++) cnt[d(i)]++;
    for(int i=1;i<=9;i++)
        for(int j=1;j<=9;j++)
            for(int k=1;k<=9;k++)
                if(i*j%9==k%9) res+=cnt[i]*cnt[j]*cnt[k];
    for(int i=1;i<=n;i++) res-=n/i;
    cout<<res<<endl;
    return 0;
}

你可能感兴趣的:(codeforces,数论)