Number obtained by reducing sum of digits of 2N into a single digit
Last Updated :
05 Apr, 2021
Given a positive integer N, the task is to find the single digit obtained after recursively adding the digits of 2N until a single digit remains.
Examples:
Input: N = 6
Output: 1
Explanation:
26 = 64. Sum of digits = 10.
Now, Sum of digits = 10. Therefore, sum is 1.
Input: N = 10
Output: 7
Explanation: 210 = 1024. Sum of digits = 7.
Naive Approach: The simplest approach to solve the problem is to calculate the value of 2N and then, keep calculating the sum of digits of number until the sum reduces to a single digit.
Time Complexity: O(log(2N))
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
After performing the operation for different values of N, it can be observed that the value repeats after every 6 numbers in the following manner:
- If N % 6 = 0, then the single digit sum will be equal to 1.
- If N % 6 = 1, then the single digit sum will be equal to 2.
- If N % 6 = 2, then the single digit sum will be equal to 4.
- If N % 6 = 3, then the single digit sum will be equal to 8.
- If N % 6 = 4, then the single digit sum will be equal to 7.
- If N % 6 = 5, then the single digit sum will be equal to 5.
Follow the steps below to solve the problem:
- If N % 6 is 0 then print 1.
- Otherwise, if N % 6 is 1 then print 2.
- Otherwise, if N % 6 is 2 then print 7.
- Otherwise, if N % 6 is 3 then print 8.
- Otherwise, if N % 6 is 4 then print 7.
- Otherwise, if N % 6 is 5 then print 5.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findNumber( int N)
{
int ans[6] = { 1, 2, 4, 8, 7, 5 };
return ans[N % 6];
}
int main()
{
int N = 6;
cout << findNumber(N) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int findNumber( int N)
{
int []ans = { 1 , 2 , 4 , 8 , 7 , 5 };
return ans[N % 6 ];
}
public static void main(String args[])
{
int N = 6 ;
System.out.println(findNumber(N));
}
}
|
Python3
def findNumber(N):
ans = [ 1 , 2 , 4 , 8 , 7 , 5 ]
return ans[N % 6 ]
if __name__ = = "__main__" :
N = 6
print (findNumber(N))
|
C#
using System;
class GFG{
static int findNumber( int N)
{
int []ans = {1, 2, 4, 8, 7, 5};
return ans[N % 6];
}
public static void Main()
{
int N = 6;
Console.WriteLine(findNumber(N));
}
}
|
Javascript
<script>
function findNumber(N)
{
let ans = [ 1, 2, 4, 8, 7, 5 ];
return ans[N % 6];
}
let N = 6;
document.write(findNumber(N) + "<br>" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...