We want the lucky lucky number to be as small as possible. Thus, we want the number to have maximum number of 4’s placed in the beginning of the number. We can write N = 7Q + R, i.e, R = N mod 7.
If R = 0, count of 4 = 7Q and count of 7 = 0
If R = 1, count of 4 = 7*(Q-1) and count of 7 = 8 ( Thus we are removing some 4’s and placing some 7’s instead. We are trying to remove only the minumum required number of 4’s )
If R = 2, count of 4 = 7*(Q-2) and count of 7 = 16
If R = 3, count of 4 = 7*(Q-3) and count of 7 = 24
If R = 4, count of 4 = 7Q and count of 7 = 4
If R = 5, count of 4 = 7*(Q-1) and count of 7 = 12
If R = 6, count of 4 = 7*(Q-2) and count of 7 = 20
Whenever, count of 4 becomes negative, in any of the above cases, it is impossible to form a lucky lucky number.
Well i finally figured it out. Tester’s solution is helpful once you try to solve with pen and paper
Although i cant seem to understand why submissions of other users are not available.
Alternative approach to it is as follows:
Suppose y is the no of digits 7. it can be expressed as y=4k (Y must be divisible by 4) ans is going to be
N-y. Now, (N-y)%7 = 0 as no. digits (4) to be divisible by 7.
=>(N-4k)%7=0 =>(N%7)-[(4%7) * (k%7)]%7=0
=>(N%7)=[4*(k%7)]%7
=>on comparing ,List of LHS values=[0,1,2,3,4,5,6] and corresponding RHS values of k=[0,2,4,6,1,3,5]. as can be seen K value is obtained from N%7 as [2*(N%7)]%7.
once you find k you get no. of digits (7) as 4k .you can then subtract this value from N.
If this value is less than 0 ans is -1 else ans=N-4k.
Here is the link to my solution.My JAVA SOLUTION