samedi 6 juin 2020

Recursive Sum in C++ [closed]

Could you please let me know how to fix the output to be 5? This is a Hackerrank challenge in C++.

Input:

3546630947312051453014172159647935984478824945973141333062252613718025688716704470547449723886626736 100000

We define super digit of an integer using the following rules:

Given an integer, we need to find the super digit of the integer.

If has only digit, then its super digit is . Otherwise, the super digit of is equal to the super digit of the sum of the digits of . For example, the super digit of will be calculated as:

//Recursive digit
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int rds(long long int P)
{
    // printf("\nP%lld",P);
    if (P / 10 == 0)
        return P;

    long long int temp = P, sum = 0;
    while (P != 0)
    {
        int P1 = P % 10;
        sum = sum + P1;
        P = P / 10;
    }

    return rds(sum);

}
int main() {
    long int d;
    int P, ans, n;
    scanf_s("%ld %d", &d, &n);
    double temp = d, sum = 0;
    while (d != 0)
    {
        int P1 = d % 10;
        sum = sum + P1;
        d = d / 10;
    }
    // printf("%lf",sum);
    sum = sum * n;
    ans = rds(sum);
    printf("%d", ans);
    return 0;

}

Aucun commentaire:

Enregistrer un commentaire