We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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
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.
intnum1(longlongintz){if(z<=9){returnz;}longlongintsum=0;longlongintm=0;while(z!=0){m=z%10;sum=sum+m;z=z/10;}returnnum1(sum);}// Complete the superDigit function below.intsuperDigit(stringn,intk){longlongintsum=0;longlongintm;for(inti=0;i<n.size();i++){sum+=n[i]-'0';}returnnum1(sum*k);}
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
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);
}
*/
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'?
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.
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 .
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));
}
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 ( + "" )
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?
@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).
@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.
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!
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));
}
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)
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);
}
intnum1(longlongintz){if(z<=9){returnz;}longlongintsum=0;longlongintm=0;while(z!=0){m=z%10;sum=sum+m;z=z/10;}returnnum1(sum);}// Complete the superDigit function below.intsuperDigit(stringn,intk){longlongintsum=0;longlongintm;for(inti=0;i<n.size();i++){sum+=n[i]-'0';}returnnum1(sum*k);}
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);
}
Recursive Digit Sum
You are viewing a single comment's thread. Return to all comments →
More Python solutions here.
can you pls explain this logic. why it works?
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)
PHP Solution
return bcmod(bcmul($n,$k),'9')?:9;
very nice!!
Thanx for contribution . Why echo 9;
If the remainder is zero( when we perform (n*k)%9) it means the sum of digits is 9.
function superDigit(k) { n,res ? $res : '9'; }
Why this code doesn't work in Javascript? I rewrite it to JS with the same logic
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; }
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.
Because n here in String.
thanx bro!!!
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
If we take n = 88, k = 2, then
8 + 8 + 8 + 8 = 16 + 16
But (n*k) gives 88*2 = 176
16 + 16 = 32 => superdigit(32) = 5 88 * 2 = 176 => 176 mod 9 = 5
it's a arithmetic trick to get the result
the trick is that 88*2 = 16+160 and superdigit(160)=superdigit(16)
Can you please provide any refernces for math like this. Thank you in Advance:)
here is problem solution in java python c++ c and javascript programming.
HackerRank Recursive Digit Sum solution
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
Here's the C++ Code, All test cases passing
Can you explain why doesn't it overflow in test case 9?
hey when the range of n is so large then how did your code got get all test cases passed .
I avoided % and / and passed all tests in cpp.
can u explain if the n is string how u are converting it in int
use function stoi( )
using ASCII, Since all numerical characters will be in series in ASCII table. eg. '9' - '0' = 9 and so on
using ASCII value like this : (int)s[i]-'0'
Can you please explain why you called num1 function by passing sum*k
I have tried to explain this in a video https://youtu.be/4LFuarM8j9Q
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
cool math solution.. but we should use recursive implementation here...
C# Recursive:
Can you please explain what's your logic?
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))
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); } */
Totally agree with you. Here's what I did in Python:
This does not pass all performance tests.
It does, though :)
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?
I hate recursion, forgot return keyword return after if clause and was wondering why my code wasn't working from the last 3 hours :'(
Instead of
; it should be
Instead of
x if x else 9
you can just dox or 9
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'?
it means: if x>0 then return x because if x=0 and 0==false then return 9
https://en.wikipedia.org/wiki/Modular_arithmetic
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.
memoize your results that helped me in solving in js with recursion
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 .
Java 8 Solution (with Recursion)
I use the same solution above in JS and it sadly times out--I guess the JVM beats node.js in runtime speeds
@drzaiusx11 This recursive JavaScript solution has passed all test cases in Node.js:
JavaScript Solution (with Recursion)
can you please explain why you wrote this +a + +b instead of a+b?. i tried running a+b, but it failed.
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 ( + "" )
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?
@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).
then why the hell we are getting time error when using for loop but not when using streams :(
@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.
This is the most elegant solution for Java I have seen
@rafaelcfreire You're welcome! And this is the true power of Java 8.
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!
@anirbansaha77 This recursive JavaScript solution has passed all test cases in Node.js:
JavaScript Solution (with Recursion)
Java 8 Solution (with Recursion)
Same in C++. Recursive solution causes Stack Overflow in the huge test cases (7,8,9).
yeah, same, so what did you do about it?
@carnegiehall This recursive JavaScript solution has passed all test cases in Node.js:
JavaScript Solution (with Recursion)
python3 solution passed.
Really nice code. Thank you.
Does this really work?
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:
wow !!
Nothing smart in this approach.
N can be as large as 10^100000. Therefore...
Here is recursive solution
It's not really working for all of the test cases.
use
num = (num + n%10 )%9;
This code is working
awesome code man. my function is exactly same as urs but I am unable to break the string.
why it didn't throw runtime error?? this solution includes many loops :\
@Singhalr31 Well, based on the comments from @swapnilsingh1023 : "It's not really working for all of the test cases." :(
WTF man!!!
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));
Here's the C++ Code, All test cases passing
If we need double digit output then it should be (n * k % 99). Right??
nope.
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);
This solution is crazy. Thanks for this solution.
Amazing, but using recursive function, it could be written in Python as
Amazing solution!!!
buddhi bahut tez h tumari
this is Recursive question. your answer is wrong. there is no recursive