Queries on sum of odd number digit sums of all the factors of a number in C++

C++Server Side ProgrammingProgramming

In this program, we are given Q queries, each query has a positive integer N. Our task is to create a program to solve queries on sum of odd number digit sums of all the factors of a number in C++.

Problem description − To solve each query, we need to find all the factors of the number N. Then add all factors having the digit sum as odd. And return the final sum for each query.

Let’s take an example to understand the problem,

Input

Q = 2, queries = {15, 8}

Output

8 1

Explanation

For query 1: N = 15, factors of 15 are 1, 3, 5, 15.

sum of odd digits in factors is 1 + 3 + 5 = 8

For query 2: N = 8, factors of 8 are 1, 2, 4, 8.

sum of odd digits in factors is 1 = 1

Solution Approach

To solve this problem, we need to sum of odd digit of all numbers. From which we will calculate the factors and then add them for the result. To make this sum of digit process each we can use precomputed values. For example, the sum of number 41 can be found as the sum of odd digits of 4 + odd digits of 3.

After creating the oddDigitSum array, we will find all the numbers that can divide the given number. Then, we will add all odd digits using the oddDigitSum array.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
#define N 99999

void calcOddDigitSum(int oddDigitSum[]) {

   for (int i = 1; i < N; i++)
   oddDigitSum[i] = oddDigitSum[i / 10] + (i & 1) * (i % 10);
}

void findFactorSum(int oddDigitSum[], int factorSum[]) {

   for (int i = 1; i < N; i++)
   for (int j = i; j < N; j += i)
   factorSum[j] += oddDigitSum[i];
}

int main(){
   int Q = 3;
   int query[] = { 5, 154, 98 };
   int oddDigitSum[N];
   int factorSum[N];
   calcOddDigitSum(oddDigitSum);
   findFactorSum(oddDigitSum, factorSum);
   for (int i = 0; i < Q; i++)
   cout<<"For query "<<(i+1)<<": The sum of odd number digit sums of all the factors of a number is "<<factorSum[query[i]]<<endl;
   return 0;
}

Output

For query 1: The sum of odd number digit sums of all the factors of a
number is 6
For query 2: The sum of odd number digit sums of all the factors of a
number is 31
For query 3: The sum of odd number digit sums of all the factors of a
number is 27
raja
Published on 06-Aug-2020 10:58:13
Advertisements