Open In App

Minimum Possible sum of digits in a positive multiple of N

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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)



Last Updated : 08 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads