Given two positive number N and X. The task is to find the sum of digits of a number formed by N repeating X number of times until sum become single digit.
Examples :
Input : N = 24, X = 3
Output : 9
Number formed after repeating 24 three time = 242424
Sum = 2 + 4 + 2 + 4 + 2 + 4
= 18
Sum is not the single digit, so finding
the sum of digits of 18,
1 + 8 = 9
Input : N = 4, X = 4
Output : 7
As discussed in this post, recursive sum of digits is 9 if number is multiple of 9, else n % 9. Since divisibility and modular arithmetic are compatible with multiplication, we simply find result for single occurrence, multiply result with x and again find the result.
How does this work?
Lets N = 24 and X = 3.
So, sumUntilSingle(N) = 2 + 4 = 6.
Multiplying 6 by 3 = 18
sumUntilSingle(18) = 9.
Below is the implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
int digSum( int n)
{
if (n == 0)
return 0;
return (n % 9 == 0) ? 9 : (n % 9);
}
int repeatedNumberSum( int n, int x)
{
int sum = x*digSum(n);
return digSum(sum);
}
int main()
{
int n = 24, x = 3;
cout << repeatedNumberSum(n, x) << endl;
return 0;
}
|
Java
class GFG {
static int digSum( int n)
{
if (n == 0 )
return 0 ;
return (n % 9 == 0 ) ? 9 : (n % 9 );
}
static int repeatedNumberSum( int n, int x)
{
int sum = x * digSum(n);
return digSum(sum);
}
public static void main (String[] args)
{
int n = 24 , x = 3 ;
System.out.println(repeatedNumberSum(n, x));
}
}
|
Python3
def digSum(n):
if n = = 0 :
return 0
return (n % 9 = = 0 ) and 9 or (n % 9 )
def repeatedNumberSum(n, x):
sum = x * digSum(n)
return digSum( sum )
n = 24 ; x = 3
print (repeatedNumberSum(n, x))
|
C#
using System;
public class GFG
{
static int digSum( int n)
{
if (n == 0)
return 0;
return (n % 9 == 0) ? 9 : (n % 9);
}
static int repeatedNumberSum( int n, int x)
{
int sum = x * digSum(n);
return digSum(sum);
}
public static void Main ()
{
int n = 24, x = 3;
Console.Write( repeatedNumberSum(n, x));
}
}
|
PHP
<?php
function digSum( $n )
{
if ( $n == 0)
return 0;
return ( $n % 9 == 0) ? 9 : ( $n % 9);
}
function repeatedNumberSum( $n , $x )
{
$sum = $x * digSum( $n );
return digSum( $sum );
}
$n = 24; $x = 3;
echo repeatedNumberSum( $n , $x );
?>
|
Javascript
<script>
function digSum(n)
{
if (n == 0)
return 0;
return (n % 9 == 0) ? 9 : (n % 9);
}
function repeatedNumberSum(n, x)
{
sum = x * digSum(n);
return digSum(sum);
}
let n = 24;
let x = 3;
document.write(repeatedNumberSum(n, x));
</script>
|
Output :
9
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
25 Aug, 2021
Like Article
Save Article