Minimum Possible sum of digits in a positive multiple of N
Last Updated :
08 May, 2023
Given a number N, find the minimum possible sum of digits that can be obtained from a positive Multiple of N. Constraints : 1<=N<=10^5. Examples:
Input : N = 6
Output : 3
Explanation: 6*2 = 12, sum of digits is 1+2 = 3.
Input : N = 20
Output : 1
20*5 = 100, sum of digits is 1+0+0=1
Approach : The problem is totally based on observation. For N = 6, the answer is 12. So we can write 12 as : 1-(*10)-->10--(+1)-->11--(+1)-->12. What the sequence describes is we can write any number >=1, as the sum's of +1 and product of *10's, starting with 1. Another observation is, when we add +1 to the digit, the digit sum increases by +1, unless the last digit is 9. The second observation is, when we multiply the digit by 10, sum of digits remains constant. Now, since we want a multiple of N, so any multiple of N % N will be 0. So, taking the above analysis, we can build a graph of K vertices, for any vertex X, the weight of node from X to X+1 will be one, and weight of node from X to (X*10)%N will be 0. We took modulo N since the vertex lies within 0 to N-1. The answer will be the shortest distance from 1 to 0, because of (Any multiple of N) mod N = 0. We can use Dijkstra's theorem to find the shortest distance between 1 and 0. Let it be d. Answer will be 1+d, as we have also to consider edge 0 to 1. The time complexity of this solution will be O(E+VLogV) = O(N+NLogN) = O(NlogN) as we will travel at most N vertices and Edges. One more thing to note is, since, after xyz..9, the next digit will be abc..0, but it will not affect our answer. Proof: lets take example of N = 11, answer is 2. It is from 11*1 = 11 and 11*10 = 110. Since 110 is a 10's multiple of N and also an answer, either we have already hit the answer because if 110 is some 10's multiple of N, then there must exist a number less than this with no leading 0's in our answer, that is 11. So either we will surpass 10's multiple of N, if it is not an answer, or we will have already hit the answer before if some 10's multiple of N is in answer. Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
const int Maxx = 100005;
int N;
vector<pair<int, int> > Graph[Maxx];
/// Dijkartas algorithm to find the shortest distance
void Dijkartas(int source)
{
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > > PQ;
// Initialize all distances to be infinity
vector<int> Distance(N + 2, 1e9);
// Push source in Priority Queue
PQ.push(make_pair(0, source));
int src = source;
Distance[src] = 0;
while (!PQ.empty()) {
int current = PQ.top().second;
PQ.pop();
for (auto& neighbours : Graph[current]) {
int v = neighbours.first;
int weight = neighbours.second;
if (Distance[v] > Distance[current] + weight) {
Distance[v] = Distance[current] + weight;
PQ.push(make_pair(Distance[v], v));
}
}
}
cout << "Minimum possible sum of digits is " <<
1 + Distance[0] << endl;
return;
}
// Function to calculate the minimum possible sum of digits
void minSumDigits(int N)
{
// Build a graph of N vertices with edge weight 1
for (int i = 1; i <= N; ++i) {
int From = (i) % N;
int To = (i + 1) % N;
int Wt = 1;
Graph[From].push_back(make_pair(To, Wt));
}
// In the same graph add weights 0 to 10's multiple of node X
for (int i = 1; i <= N; ++i) {
int From = (i) % N;
int To = (10 * i) % N;
int Wt = 0;
Graph[From].push_back(make_pair(To, Wt));
}
// Run dijkartas to find the shortest distance from 1 to 0
Dijkartas(1);
return;
}
// Driver Code
int main()
{
N = 19;
minSumDigits(N);
return 0;
}
Python3
# Python3 code to implement the approach
Maxx = 100005
Graph = [None for _ in range(Maxx)]
for i in range(Maxx):
Graph[i] = []
# / Dijkartas algorithm to find the shortest distance
def Dijkartas(source):
PQ = []
# Initialize all distances to be infinity
Distance = [1e9 for _ in range(N + 2)]
# append source in Priority Queue
PQ.append([0, source])
src = source
Distance[src] = 0
while (len(PQ) != 0):
current = PQ.pop(0)[1]
for neighbours in Graph[current]:
v = neighbours[0]
weight = neighbours[1]
if (Distance[v] > Distance[current] + weight):
Distance[v] = Distance[current] + weight
PQ.append([Distance[v], v])
print("Minimum possible sum of digits is", (1 + Distance[0]))
return
# Function to calculate the minimum possible sum of digits
def minSumDigits(N):
# Build a graph of N vertices with edge weight 1
for i in range(1, N + 1):
From = (i) % N
To = (i + 1) % N
Wt = 1
Graph[From].append([To, Wt])
# In the same graph add weights 0 to 10's multiple of node X
for i in range(1, N + 1):
From = (i) % N
To = (10 * i) % N
Wt = 0
Graph[From].append([To, Wt])
# Run dijkartas to find the shortest distance from 1 to 0
Dijkartas(1)
return
# Driver Code
N = 19
minSumDigits(N)
# This code is contributed by phasing17
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
class GFG {
static int Maxx = 100005;
static int N;
static List<List<int[]> > Graph
= new List<List<int[]> >();
/// Dijkartas algorithm to find the shortest distance
static void Dijkartas(int source)
{
List<int[]> PQ = new List<int[]>();
// Initialize all distances to be infinity
int[] Distance = new int[N + 2];
for (int i = 0; i <= N + 1; i++)
Distance[i] = 1000000000;
// Push source in Priority Queue
PQ.Add(new[] { 0, source });
int src = source;
Distance[src] = 0;
while (PQ.Count != 0) {
int current = PQ[0][1];
PQ.RemoveAt(0);
foreach(var neighbours in Graph[current])
{
int v = neighbours[0];
int weight = neighbours[1];
if (Distance[v]
> Distance[current] + weight) {
Distance[v]
= Distance[current] + weight;
PQ.Add(new[] { Distance[v], v });
}
}
}
Console.WriteLine(
"Minimum possible sum of digits is "
+ (1 + Distance[0]));
return;
}
// Function to calculate the minimum possible sum of
// digits
static void minSumDigits(int N)
{
// Build a graph of N vertices with edge weight 1
for (var i = 1; i <= N; ++i) {
int From = (i) % N;
int To = (i + 1) % N;
int Wt = 1;
List<int[]> l1 = Graph[From];
l1.Add(new[] { To, Wt });
Graph[From] = l1;
}
// In the same graph add weights 0 to 10's multiple
// of node X
for (int i = 1; i <= N; ++i) {
int From = (i) % N;
int To = (10 * i) % N;
int Wt = 0;
List<int[]> l1 = Graph[From];
l1.Add(new[] { To, Wt });
Graph[From] = l1;
}
// Run dijkartas to find the shortest distance from 1
// to 0
Dijkartas(1);
return;
}
// Driver Code
public static void Main(string[] args)
{
N = 19;
for (int i = 0; i < Maxx; i++)
Graph.Add(new List<int[]>());
minSumDigits(N);
}
}
// This code is contributed by phasing17
JavaScript
// JS code to implement the approach
let Maxx = 100005;
let N;
let Graph = new Array(Maxx);
for (var i = 0; i < Maxx; i++)
Graph[i] = new Array();
/// Dijkartas algorithm to find the shortest distance
function Dijkartas(source)
{
let PQ = [];
// Initialize all distances to be infinity
let Distance = new Array(N + 2).fill(1e9);
// Push source in Priority Queue
PQ.push([0, source]);
let src = source;
Distance[src] = 0;
while (PQ.length != 0) {
let current = PQ.shift()[1];
for (let neighbours of Graph[current]) {
let v = neighbours[0];
let weight = neighbours[1];
if (Distance[v] > Distance[current] + weight) {
Distance[v] = Distance[current] + weight;
PQ.push([Distance[v], v]);
}
}
}
console.log("Minimum possible sum of digits is", (1 + Distance[0]));
return;
}
// Function to calculate the minimum possible sum of digits
function minSumDigits(N)
{
// Build a graph of N vertices with edge weight 1
for (var i = 1; i <= N; ++i) {
let From = (i) % N;
let To = (i + 1) % N;
let Wt = 1;
Graph[From].push([To, Wt]);
}
// In the same graph add weights 0 to 10's multiple of node X
for (var i = 1; i <= N; ++i) {
let From = (i) % N;
let To = (10 * i) % N;
let Wt = 0;
Graph[From].push([To, Wt]);
}
// Run dijkartas to find the shortest distance from 1 to 0
Dijkartas(1);
return;
}
// Driver Code
N = 19;
minSumDigits(N);
// This code is contributed by phasing17
Java
// Java code to implement the approach
import java.util.*;
class GFG {
static int Maxx = 100005;
static int N;
static ArrayList<ArrayList<ArrayList<Integer> > > Graph
= new ArrayList<ArrayList<ArrayList<Integer> > >();
/// Dijkartas algorithm to find the shortest distance
static void Dijkartas(int source)
{
ArrayList<ArrayList<Integer> > PQ
= new ArrayList<ArrayList<Integer> >();
// Initialize all distances to be infinity
ArrayList<Integer> Distance
= new ArrayList<Integer>();
for (int i = 0; i <= N + 1; i++)
Distance.add(1000000000);
// Push source in Priority Queue
ArrayList<Integer> l1 = new ArrayList<Integer>();
l1.add(0);
l1.add(source);
PQ.add(l1);
int src = source;
Distance.set(src, 0);
while (PQ.size() != 0) {
int current = PQ.get(0).get(1);
PQ.remove(0);
for (ArrayList<Integer> neighbours :
Graph.get(current)) {
int v = neighbours.get(0);
int weight = neighbours.get(1);
if (Distance.get(v)
> Distance.get(current) + weight) {
Distance.set(v, Distance.get(current)
+ weight);
ArrayList<Integer> l2
= new ArrayList<Integer>();
l2.add(Distance.get(v));
l2.add(v);
PQ.add(l2);
}
}
}
System.out.println(
"Minimum possible sum of digits is "
+ (1 + Distance.get(0)));
return;
}
// Function to calculate the minimum possible sum of
// digits
static void minSumDigits(int N)
{
// Build a graph of N vertices with edge weight 1
for (var i = 1; i <= N; ++i) {
int From = (i) % N;
int To = (i + 1) % N;
int Wt = 1;
ArrayList<ArrayList<Integer> > l1
= Graph.get(From);
ArrayList<Integer> l2
= new ArrayList<Integer>();
l2.add(To);
l2.add(Wt);
l1.add(l2);
Graph.set(From, l1);
}
// In the same graph add weights 0 to 10's multiple
// of node X
for (int i = 1; i <= N; ++i) {
int From = (i) % N;
int To = (10 * i) % N;
int Wt = 0;
ArrayList<ArrayList<Integer> > l1
= Graph.get(From);
ArrayList<Integer> l2
= new ArrayList<Integer>();
l2.add(To);
l2.add(Wt);
l1.add(l2);
Graph.set(From, l1);
}
// Run dijkartas to find the shortest distance from 1
// to 0
Dijkartas(1);
return;
}
// Driver Code
public static void main(String[] args)
{
N = 19;
for (int i = 0; i < Maxx; i++)
Graph.add(new ArrayList<ArrayList<Integer> >());
minSumDigits(N);
}
}
// This code is contributed by phasing17
Output:Minimum possible sum of digits is 2
Time complexity: O(N log N) where N is the number of vertices in the graph.
Space complexity: O(N)
Similar Reads
First N terms whose sum of digits is a multiple of 10
Given an integer N, the task is to print the first N terms whose sum of digits is a multiple of 10. First few terms of the series are 19, 28, 37, 46, 55, ...Examples: Input: N = 5 Output: 19 28 37 46 55Input: N = 10 Output: 19 28 37 46 55 64 73 82 91 109 Recommended: Please try your approach on {IDE
11 min read
Smallest integer with digit sum M and multiple of N
Given two positive integers N and M, the task is to find the smallest positive integer which is divisible by N and whose digit sum is M. Print -1 if no such integer exists within the range of int. Examples: Input: N = 13, M = 32 Output: 8879 8879 is divisible by 13 and its Sum of digits of 8879 is 8
5 min read
Smallest multiple of N formed using the given set of digits
Given a set of digits S and an integer N, the task is to find the smallest positive integer if exists which contains only the digits from S and is a multiple of N. Note that the digits from the set can be used multiple times. Examples: Input: S[] = {5, 2, 3}, N = 12 Output: 252 We can observe that 2
10 min read
Maximum multiple of a number with all digits same
Given two positive integers X and Y (1 ? Y ? 105), find the maximum positive multiple (say M) of X such that M is less than 10Y and all the digits in the decimal representation of M are equal. Note: If no positive multiple exists that satisfies the conditions, return -1. Examples: Input: X = 1, Y =
7 min read
Recursive sum of digits of a number is prime or not
Given a number n, we need to find the sum of each digits of the number till the number becomes a single digit. We need to print "yes" if the sum is a prime or "no" if it is not prime. Examples: Input : 5602 Output: No Explanation: Step 1- 5+6+0+2 = 13 Step 2- 1+3 = 4 4 is not prime Input : 56 Output
5 min read
Smallest multiple of a given number made of digits 0 and 9 only
We are given an integer N. We need to write a program to find the least positive integer X made up of only digits 9's and 0's, such that, X is a multiple of N. Note: It is assumed that the value of X will not exceed 106. Examples: Input : N = 5 Output : X = 90 Explanation: 90 is the smallest number
8 min read
Minimum count of digits required to obtain given Sum
Given an integer N, the task is to find the minimum number of digits required to generate a number having the sum of digits equal to N. Examples: Input: N = 18 Output: 2 Explanation: The number with smallest number of digits having sum of digits equal to 18 is 99. Input: N = 28 Output: 4 Explanation
3 min read
Find minimum possible digit sum after adding a number d
Given a number n and a number d, we can add d to n as many times ( even 0 is possible ). The task is to find the minimum possible digit sum we can achieve by performing above operation. Digit Sum is defined as the sum of digits of a number recursively until it is less than 10.Examples: Input: n = 25
6 min read
Find the minimum number possible by changing at most one digit
Given a positive integer N consisting only two types of digits 6 and 9, the task is to generate the minimum number possible by reversing at most one digit, that is 9 becomes 6 or vice versa.Examples: Input : 9996 Output : 6996 Explanation : Changing the first digit results in 6996. Changing the seco
5 min read
Make n using 1s and 2s with minimum number of terms multiple of k
Given two positive integer n and k. n can be represented as the sum of 1s and 2s in many ways, using multiple numbers of terms. The task is to find the minimum number of terms of 1s and 2s use to make the sum n and also number of terms must be multiple of k. Print "-1", if no such number of terms ex
6 min read