Recursive Digit Sum

  • + 19 comments
    n, k = map(int, input().split())
    x = n * k % 9
    print(x if x else 9)
    

    More Python solutions here.

    • + 5 comments

      can you pls explain this logic. why it works?

      • + 5 comments

        consider this example, where n = 23, k = 3

        accoring to problem we can do it as 2+3+2+3+2+3 = 6+9 or (n*k) means (23*3) = 69 eventually which leads to 6+9 then we use modulus 9, according to decimal number system here is some interesting fact with proof being provided in the following link key to your curiosity

        cheers (y)

        • + 4 comments

          PHP Solution

          return bcmod(bcmul($n,$k),'9')?:9;
          
          • + 1 comment

            very nice!!

          • + 1 comment

            Thanx for contribution . Why echo 9;

            • + 1 comment

              If the remainder is zero( when we perform (n*k)%9) it means the sum of digits is 9.

          • + 0 comments

            function superDigit(k) { n,res ? $res : '9'; }

        • + 4 comments

          Why this code doesn't work in Javascript? I rewrite it to JS with the same logic

          • + 0 comments

            The test cases get too large for JS to represent as a 'Number'. Instead, use 'BigInt'. https://javascript.info/bigint

            function superDigit(n, k) { var value = Number((BigInt(n) * BigInt(k)) % BigInt(9)); return value ? value : 9; }

          • + 0 comments

            If it works in Python, it's slow on big numbers and a half of test cases are really big numbers. You shoud make the first pass and sum all the digits and then do the trick. You have a limit of 100.000.000.000 there which suits long type.

          • + 0 comments

            Because n here in String.

        • + 1 comment

          thanx bro!!!

          • + 0 comments

            Here is the detail explanation of this problem

            Check out the video explanations below (Telugu Videos)

            https://www.youtube.com/watch?v=mfGxzwRtFGQ - Implementation https://www.youtube.com/watch?v=Tzipp9yucwM&t=4s - Debugging https://www.youtube.com/watch?v=yncwkZ1mmPY - Hackerrank Validation

        • + 2 comments

          If we take n = 88, k = 2, then

          8 + 8 + 8 + 8 = 16 + 16

          But (n*k) gives 88*2 = 176

          • + 0 comments

            16 + 16 = 32 => superdigit(32) = 5 88 * 2 = 176 => 176 mod 9 = 5

            it's a arithmetic trick to get the result

          • + 0 comments

            the trick is that 88*2 = 16+160 and superdigit(160)=superdigit(16)

        • + 0 comments

          Can you please provide any refernces for math like this. Thank you in Advance:)

      • + 1 comment
        [deleted]
        • + 1 comment

          here is problem solution in java python c++ c and javascript programming.

          HackerRank Recursive Digit Sum solution

          • + 0 comments

            Here is the detail explanation of this problem

            Check out the video explanations below (Telugu Videos)

            https://www.youtube.com/watch?v=mfGxzwRtFGQ - Implementation https://www.youtube.com/watch?v=Tzipp9yucwM&t=4s - Debugging https://www.youtube.com/watch?v=yncwkZ1mmPY - Hackerrank Validation

      • + 2 comments
        [deleted]
        • + 5 comments

          Here's the C++ Code, All test cases passing

          int num1(long long int z)
          {
              if(z<=9)
              {
                  return z;
              }
              long long int sum=0;
              long long int m=0;
          
              while(z!=0)
              {
                  
                  m=z%10;
                  sum=sum+m;
                  z=z/10;
          
          
              }
              return num1(sum);
          
          
          }
          
          // Complete the superDigit function below.
          int superDigit(string n, int k) {
          long long int sum=0;
          long long int m;
             for(int i=0; i<n.size(); i++){
                  sum += n[i] - '0';
              }
          
              return num1(sum*k);
          
          }
          
          • + 0 comments

            Can you explain why doesn't it overflow in test case 9?

          • + 0 comments

            hey when the range of n is so large then how did your code got get all test cases passed .

          • + 0 comments

            I avoided % and / and passed all tests in cpp.

          • + 4 comments

            can u explain if the n is string how u are converting it in int

            • + 0 comments

              use function stoi( )

            • + 0 comments

              using ASCII, Since all numerical characters will be in series in ASCII table. eg. '9' - '0' = 9 and so on

            • + 0 comments

              using ASCII value like this : (int)s[i]-'0'

          • + 0 comments

            Can you please explain why you called num1 function by passing sum*k

      • + 0 comments

        I have tried to explain this in a video https://youtu.be/4LFuarM8j9Q

      • + 0 comments

        First consider case where the input is only one digit: superdigit(x where x<10)

        its obvious that superdigit(x) =x mod 9 if x is smaller than 9. Only x==9 will be an edge case. Now we consider a decimal number such as 100*a+10*b+c and we can prove that 100*a+10*b+c mod 9 =(a+b+c) mod 9 +(99*a+9*b)mod 9 100*a+10*b+c mod 9=0+(a+b+c) mod 9 which means mod9 conserves through recursive superdigit operation.

        Then if we have any given input a, we can draw a chain like a-b-c-..-x where x is a single digit number.

        From the previous paragraph, we know that amod9==bmod9==cmod9 .... ==xmod9

        From the property defined in superdigit operation, we know that supdigit(a)==superdigit(b)==superdigit(c)==...superdigit(x)

        Since in the first pragraph, we showed that superdigit(x)==xmod9 despite the edge case where x==9. This tells us that tails of two chains are equal, so the heads of two chains must also be equal except x==9 case.

        Therefore supdigit(a)==a mod 9 if a mod 9!=0 supdigit(a)==9 if a mod9 ==0

        which

    • + 2 comments

      cool math solution.. but we should use recursive implementation here...

      • + 2 comments

        C# Recursive:

        static int superDigit(string n, int k) {
                StringBuilder sb = new StringBuilder();
                for(int i = 0; i < k % 9; i++){
                    sb.Append(n);
                }
                return Helper(sb);
            }
        
            static int Helper(StringBuilder str){
                if(str.Length == 1)
                    return Convert.ToInt32(str.ToString());
                else{
                    long sum = 0;
                    for(int i = 0; i < str.Length; i++){
                        sum += Convert.ToInt32(str[i].ToString());
                    }
                    return Helper(new StringBuilder(sum.ToString()));
                }
            }
        
        • + 1 comment

          Can you please explain what's your logic?

          • + 0 comments

            def modu (n): return sum(int(i) for i in str(n))

            def superDigit(n): if n < 10: print (n) else: superDigit(modu(n))

            n,k = input().split() superDigit(modu(int(n)) * int(k))

        • + 0 comments

          this code also work for all test:

          public static int superDigit(String n, int k) { if(n.length()==1) return Integer.parseInt(n); int sum=0; for(char c:n.toCharArray()){ sum+=(int)(c-48);
          } return superDigit(sum*(k%9)+"",1); } */

      • + 4 comments

        Totally agree with you. Here's what I did in Python:

        def superDigit(n, k):
            if len(n)==1:
                return n
            return superDigit(str(sum(map(int, n))*k),1)
        
        • + 1 comment

          This does not pass all performance tests.

          • + 1 comment

            It does, though :)

        • + 0 comments

          Hey 7ovana,

          I am try to do the code as below. But not pass all the test and shows that time exceed. Any idea why this approach is slower than yours, please?

          def superDigit(n, k):
              if len(n) == 1:
                  return n
              
              n = n * k 
              
              while len(n) > 1:
                  n = superDigit_helper(n)
              return n
          
          def superDigit_helper(n):
              return  str(sum(map(int, n)))
          
        • + 0 comments

          I hate recursion, forgot return keyword return after if clause and was wondering why my code wasn't working from the last 3 hours :'(

        • + 0 comments

          Instead of

          if len(n)==1:

          ; it should be

          if len(n)==1 and k==1:

    • + 1 comment

      Instead of x if x else 9 you can just do x or 9

      • + 2 comments

        Can someone provide explaination as to what "return(x if x else 9)" is doing? I understand it is returning the output, but I do not understand the logic of how because how does the proram know when to return '9' versus 'x'?

        • + 0 comments

          it means: if x>0 then return x because if x=0 and 0==false then return 9

        • + 0 comments

          https://en.wikipedia.org/wiki/Modular_arithmetic

    • + 5 comments

      I don't like the categorization of this problem as recursion. Some of the test cases are so huge that recursion causes stack overflows / timeouts in many languages (I tried both JS and Python). This modulus solution is great, but it's a little misleading to ask you to write it recursively when this solution is so much more elegant.

      • + 2 comments

        memoize your results that helped me in solving in js with recursion

        • + 1 comment

          Even when i used lru_cache in python , it failed 3 to 4 test cases. Then i tried using a custom memo, it still failed those test cases by exceeding recursion limit. Could you elaborate a bit .

          • + 5 comments

            Java 8 Solution (with Recursion)

            static int superDigit(String n, int k) {
                n = n.chars().mapToLong(Character::getNumericValue).sum() * k
                        + "";
                return (n.length() > 1) ? superDigit(n, 1) :
                                            Character.getNumericValue(n.charAt(0));
            }
            
            • + 1 comment

              I use the same solution above in JS and it sadly times out--I guess the JVM beats node.js in runtime speeds

              • + 1 comment

                @drzaiusx11 This recursive JavaScript solution has passed all test cases in Node.js:

                JavaScript Solution (with Recursion)

                function superDigit(n, k) {
                    n = n.split("").reduce((a, b) => +a + +b) * k + "";
                    return (n.length > 1) ? superDigit(n, 1) : n.charAt(0);
                }
                
                • + 1 comment

                  can you please explain why you wrote this +a + +b instead of a+b?. i tried running a+b, but it failed.

                  • + 0 comments

                    Late reply, but the reason this works is: ( +a + +b ) coerces each variable with a unary operator ( + ), to assure the addition of two integers and not the concatination of two strings. Then, the integer is being multiplied by the concat multiplier ( * k ) and converted back to a string ( + "" )

            • + 1 comment

              This seems awesome. I just wanted to know why you used n.chars().mapToLong(Character::getNumericValue).sum() * k + ""; I understand you are trying to sum all the characters and multiply by k and converting back to string but this notation i have never used. is this faster than say doing a for loop to find this out? doesnt this take O(x) time where x is the no of chars in string n?

              • + 1 comment

                @Utsav1998 Using Java 8 Stream may NOT be faster than a "for loop" but the Stream is more "fluent" in terms of Functional Programming, and the complexity of that stream is indeed O(x).

                • + 1 comment

                  then why the hell we are getting time error when using for loop but not when using streams :(

                  • + 0 comments

                    @Singhalr31 For a simple "for" loop (without Collections or Maps), Java 8 Stream "could be" overkill. If you need to iterate over a "LARGE" Collection (or Map) , however, Java 8 may be faster because you could avoid creating LOTS of "intermediate" Objects by simply streaming data in the Collection from one operation to another.

            • + 1 comment

              This is the most elegant solution for Java I have seen

              • + 0 comments

                @rafaelcfreire You're welcome! And this is the true power of Java 8.

            • + 0 comments

              Wow! , this is really awesome. Even i used BigInteger for the problem but TLE occured in test case 8 and 9. Thank you so much @tat_lim for the solution!

        • + 0 comments

          @anirbansaha77 This recursive JavaScript solution has passed all test cases in Node.js:

          JavaScript Solution (with Recursion)

          function superDigit(n, k) {
              n = n.split("").reduce((a, b) => +a + +b) * k + "";
              return (n.length > 1) ? superDigit(n, 1) : n.charAt(0);
          }
          
      • + 0 comments

        Java 8 Solution (with Recursion)

        static int superDigit(String n, int k) {
            n = n.chars().mapToLong(Character::getNumericValue).sum() * k
                    + "";
            return (n.length() > 1) ? superDigit(n, 1) :
                                        Character.getNumericValue(n.charAt(0));
        }
        
      • + 1 comment

        Same in C++. Recursive solution causes Stack Overflow in the huge test cases (7,8,9).

        • + 0 comments

          yeah, same, so what did you do about it?

      • + 0 comments

        @carnegiehall This recursive JavaScript solution has passed all test cases in Node.js:

        JavaScript Solution (with Recursion)

        function superDigit(n, k) {
            n = n.split("").reduce((a, b) => +a + +b) * k + "";
            return (n.length > 1) ? superDigit(n, 1) : n.charAt(0);
        }
        
      • + 5 comments

        python3 solution passed.

        def superDigit(n, k):
            
            def add_digits(string):
                if len(string) == 1:
                    return string
                result = sum(int(s) for s in string)
                return add_digits(str(result))
            
            start = sum(int(s) for s in n) * k
            return add_digits(str(start))
        
        • + 0 comments

          Really nice code. Thank you.

        • + 1 comment

          Does this really work?

          • + 0 comments

            Yes, this solution uses recursion and also does not need the % 9 trick. You can show to yourself that "k" can be multiplied after summing up n by using the problem statement example, n = 9875, and change k from 1 to 5. You'll see that the solutions are multiples of one another, except for when it is 10 (which results in having to sum up the integers)

            Also, you can simplify this answer further, so as not to have a "start" variable:

                def superDigit(n, k):
                        sd = sum(int(s) for s in n)
                        if sd*k < 10:
                                return sd*k
                        else:
                                return superDigit(str(sd*k), 1)
            
        • + 1 comment
          [deleted]
    • + 0 comments

      wow !!

    • + 0 comments

      Nothing smart in this approach.

      N can be as large as 10^100000. Therefore...

    • + 0 comments
      n, k = map(int, input().split())
      print( n * k % 9 or 9)
      
    • + 3 comments

      Here is recursive solution

      static int superDigit(String n, int k) {
            long num = 0; 
            for(int i=0; i<n.length(); i++) {
                num += Integer.parseInt(n.charAt(i)+"");
            } 
            num =  helper(num*k);
            int num2 = (int) num;
            return num2;
          }
          private static long helper(long n) {
            if(n<10) {
              return n; 
            }
            else {
              int num = 0;
              while(n>0) {
                num += n % 10;
                n = n/10; 
              } 
              return helper(num); 
            }
           
           }     
      
      • + 2 comments

        It's not really working for all of the test cases.

        • + 0 comments

          use

          num = (num + n%10 )%9;

        • + 0 comments

          This code is working

          static long getNum(String n){
                  long num = 0;
                  for(char c : n.toCharArray())
                      num += Character.digit(c, 10);
                  return num;
              }
              static int superDigit(String n){
                  System.out.println(n);
                  if(n.length() <= 1) return Integer.parseInt(n);
                  return superDigit(String.valueOf(getNum(n))); 
              }
              static int superDigit(String n, int k) {
                  return superDigit(String.valueOf(k * getNum(n)));
              }
          
      • + 0 comments

        awesome code man. my function is exactly same as urs but I am unable to break the string.

      • + 1 comment

        why it didn't throw runtime error?? this solution includes many loops :\

        • + 0 comments

          @Singhalr31 Well, based on the comments from @swapnilsingh1023 : "It's not really working for all of the test cases." :(

    • [deleted]
      + 0 comments
      1. I see no recursion
      2. this solution is poorly documented and is an example of bad code from production quality point of view
    • + 0 comments

      WTF man!!!

    • + 0 comments

      Can any one help me to check the issue. iam not able pass some of test cases with larger input. please hlp me out static int superDigit(long l) { if (l == 0)
      return 0; return (int)((l % 9 == 0) ? 9 : (l % 9));

      }
      
      static long  getDigit(String in, int k)
      {
          long res = 0;
          for(int i=0;i<in.length();i++)
          res=res*10+in.charAt(i)-'0';
          return Math.abs(res*k);
      }
      
    • + 0 comments

      Here's the C++ Code, All test cases passing

      int num1(long long int z)
      {
          if(z<=9)
          {
              return z;
          }
          long long int sum=0;
          long long int m=0;
      
          while(z!=0)
          {
              
              m=z%10;
              sum=sum+m;
              z=z/10;
      
      
          }
          return num1(sum);
      
      
      }
      
      // Complete the superDigit function below.
      int superDigit(string n, int k) {
      long long int sum=0;
      long long int m;
         for(int i=0; i<n.size(); i++){
              sum += n[i] - '0';
          }
      
          return num1(sum*k);
      
      }
      
    • + 1 comment

      If we need double digit output then it should be (n * k % 99). Right??

      • + 0 comments

        nope.

    • + 0 comments

      Note: In this particular problem instead of using maths use recursion as this problem comes under recursion category.

      this is my recursiove solution to this particular problem quite simple to understand.

      public static int recursiveSum(long n){ if(n<10){ return (int)n; } long sum=0; while(n!=0){ long rem = n%10; sum+=rem; n/=10; } return recursiveSum(sum);

      }
      
      // Complete the superDigit function below.
      static int superDigit(String n, int k) {
      
          //note: we need to use long here to get the correct solution.
          int i=0;
          long sum=0;
          while(i!=n.length()){
              char ch =n.charAt(i);
              sum += Long.parseLong(ch+""); 
              i++;
          }
          sum*=k;
          String str=String.valueOf(sum);
      
          return recursiveSum(sum);
      
      }
      
    • + 0 comments

      This solution is crazy. Thanks for this solution.

    • + 1 comment

      Amazing, but using recursive function, it could be written in Python as

      def superDigit(n, k):

      if len(str(n)) == 1:
          return n    
      return superDigit(sum([int(i) for i in list(str(n))])*k,1)
      
      • + 0 comments

        Amazing solution!!!

    • + 0 comments

      buddhi bahut tez h tumari

    • + 0 comments

      this is Recursive question. your answer is wrong. there is no recursive