digit counting problem

digit count

Time limit : 1.0s    Memory limit : 256.0MB

Problem Description

Given two positive integers n and m, among the integers 1 to n, how many numbers have the sum of the squares of each digit equal to m?

For example, when n=100 and m=5, only the sum of the squares of digits 12 and 21 is 5, so the answer is 2.

input format

The first line of input contains two integers n and m separated by a space.

output format

The output line contains an integer representing the answer.

sample input   

100 5

sample output   

2

Evaluation use case scale and agreement

For 40% of the evaluation cases, 1 <= n <= 1000, 1 <= m <= 1000.

For 100% of the evaluation cases, 1 <= n <= 1000000, 1 <= m <= 1000.

Solution part:

This problem can use a loop to enumerate each number from 1 to n, and calculate whether the sum of the squares of its digits is equal to m. If it is equal to m, the counter is incremented by 1. The final value of the counter is the answer.

#include <iostream>
#include <string>

using namespace std;

int square_sum(int n, int m) {
    int count = 0;
    for (int i = 1; i <= n; i++) {
        string digits = to_string(i);
        int square_sum = 0;
        for (char d : digits) {
            int digit = d - '0';
            square_sum += digit * digit;
        }
        if (square_sum == m) {
            count++;
        }
    }
    return count;
}

int main() {
    int n;
    int m;
    cin >> n >> m;
    cout << square_sum(n, m);
    return 0;
}

Guess you like

Origin blog.csdn.net/FlyFree56/article/details/130783083