Minimum count of numbers required ending with 7 to sum as a given number
Last Updated :
26 May, 2021
Given an integer N, the task is to find the minimum count of numbers ending with 7 such that the sum of these numbers is N.
Examples:
Input: N = 38
Output: 4
7 + 7 + 7 + 17
Input: N = 46
Output: -1
46 cannot be represented as the sum
of integers ending with 7.
Input: N = 215
Output: 5
7 + 7 + 7 + 7 + 187
Approach:
- First observation here is that every number greater than or equal to 70 can always be written as the sum of numbers all ending with 7. For example, for 82 the last digit is 2, so at least 6 numbers ending with 7 are required i.e. (7 * 6 = 42). An array hasharr[] can be created where hasharr[i] represents the minimum number of numbers required having the last digit as 7 so the resultant sum has the last digit as i.
- If the number is less than 70 then N has to be checked whether it is less than the sum of the minimum number of numbers ending with digit seven 7. If it is then it is not possible and print -1, otherwise if it is greater or equal than it is possible.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int TEN = 10;
int minCount( int n)
{
int hasharr[TEN] = { 10, 3, 6, 9, 2, 5, 8, 1, 4, 7 };
if (n > 69)
return hasharr[n % TEN];
else {
if (n >= hasharr[n % TEN] * 7)
return (hasharr[n % TEN]);
else
return -1;
}
}
int main()
{
int n = 38;
cout << minCount(n);
return 0;
}
|
Java
class GFG {
static int minCount( int n)
{
int [] hasharr = { 10 , 3 , 6 , 9 , 2 ,
5 , 8 , 1 , 4 , 7 };
if (n > 69 )
return hasharr[n % 10 ];
else
{
if (n >= hasharr[n % 10 ] * 7 )
return (hasharr[n % 10 ]);
else
return - 1 ;
}
}
public static void main (String[] args)
{
int n = 38 ;
System.out.println(minCount(n));
}
}
|
Python3
def minCount(n):
hasharr = [ 10 , 3 , 6 , 9 , 2 ,
5 , 8 , 1 , 4 , 7 ]
if (n > 69 ):
return hasharr[n % 10 ]
else :
if (n > = hasharr[n % 10 ] * 7 ):
return hasharr[n % 10 ]
else :
return - 1
n = 38 ;
print (minCount(n))
|
C#
using System;
class GFG{
static int minCount( int n)
{
int [] hasharr = { 10, 3, 6, 9, 2,
5, 8, 1, 4, 7 };
if (n > 69)
return hasharr[n % 10];
else
{
if (n >= hasharr[n % 10] * 7)
return (hasharr[n % 10]);
else
return -1;
}
}
public static void Main (String[] args)
{
int n = 38;
Console.WriteLine(minCount(n));
}
}
|
Javascript
<script>
function minCount(n)
{
let hasharr = [ 10, 3, 6, 9, 2,
5, 8, 1, 4, 7 ];
if (n > 69)
return hasharr[n % 10];
else
{
if (n >= hasharr[n % 10] * 7)
return (hasharr[n % 10]);
else
return -1;
}
}
let n = 38;
document.write(minCount(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...