Showing posts with label Recursive digit sum hacker rank solution in c. Show all posts
Showing posts with label Recursive digit sum hacker rank solution in c. Show all posts

Tuesday, 12 December 2017

Recursive digit sum hacker rank solution in c

Problem:
https://www.hackerrank.com/challenges/recursive-digit-sum/

Solution is very simple for this problem but since the value of n can be 10^1000000 which cannot be stored in a variable of any data type in c, we need to store each digit in n in a string.

13 points solution is as follows: Using the fact that 
 recursive sum of digits is 9 if number is multiple of 9, else n % 9

#include<stdio.h>

int main()
{
        unsigned long long int n,k;
        scanf("%llu%llu",&n,&k);
        int ans=((n%9)*(k%9))%9;  // ans=(n*k)%9
        if(ans)
            printf("%llu",ans);
        else
            printf("9");
}


#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int superDigit(char* n, int k) {
       int k1,i;
    k1=k%9;
    if(k1 == 0)
        return 9;
    else
    {
        int sum=0;
        for(i=0;n[i] != '\0';i++)
            sum=(sum+n[i]-48)%9;
        if((sum*k)%9 == 0)
            return 9;
        else
            return (sum*k)%9;
     }
}

int main() {
    char* n = (char *)malloc(512000 * sizeof(char));
    int k;
    scanf("%s %i", n, &k);
    int result = superDigit(n, k);
    printf("%d\n", result);
    return 0;
}