A friend of mine is interviewing for a job. One of the interview questions got me thinking, just wanted some feedback.
There are 2 non-negative integers: i and j. Gi
I know I am likely wrong but there is a very simple heuristic here since it does not involve many numbers like 2,3,5. We know that for any i,j 2^i * 5^j next sequence would be 2^(i-2) * 5^(j+1). Being a google q it must have a simple solution.
def func(i, j):
print i, j, (2**i)*(5**j)
imax=i=2
j=0
print "i", "j", "(2**i)*(5**j)"
for k in range(20):
func(i,j)
j=j+1; i=i-2
if(i<0):
i = imax = imax+1
j=0
This produces output as :
i j (2**i)*(5**j)
2 0 4
0 1 5
3 0 8
1 1 10
4 0 16
2 1 20
0 2 25
5 0 32
3 1 40
1 2 50
6 0 64
4 1 80
2 2 100
0 3 125
7 0 128
5 1 160
3 2 200
1 3 250
8 0 256
6 1 320
Why not try looking at this from the other direction. Use a counter to test the possible answers against the original formula. Sorry for the pseudo code.
for x = 1 to n
{
i=j=0
y=x
while ( y > 1 )
{
z=y
if y divisible by 2 then increment i and divide y by 2
if y divisible by 5 then increment j and divide y by 5
if y=1 then print i,j & x // done calculating for this x
if z=y then exit while loop // didn't divide anything this loop and this x is no good
}
}
Here is my solution
#include <stdio.h>
#include <math.h>
#define N_VALUE 5
#define M_VALUE 5
int n_val_at_m_level[M_VALUE];
int print_lower_level_val(long double val_of_higher_level, int m_level)
{
int n;
long double my_val;
for( n = n_val_at_m_level[m_level]; n <= N_VALUE; n++) {
my_val = powl(2,n) * powl(5,m_level);
if(m_level != M_VALUE && my_val > val_of_higher_level) {
n_val_at_m_level[m_level] = n;
return 0;
}
if( m_level != 0) {
print_lower_level_val(my_val, m_level - 1);
}
if(my_val < val_of_higher_level || m_level == M_VALUE) {
printf(" %Lf n=%d m = %d\n", my_val, n, m_level);
} else {
n_val_at_m_level[m_level] = n;
return 0;
}
}
n_val_at_m_level[m_level] = n;
return 0;
}
main()
{
print_lower_level_val(0, M_VALUE); /* to sort 2^n * 5^m */
}
Result :
1.000000 n = 0 m = 0
2.000000 n = 1 m = 0
4.000000 n = 2 m = 0
5.000000 n = 0 m = 1
8.000000 n = 3 m = 0
10.000000 n = 1 m = 1
16.000000 n = 4 m = 0
20.000000 n = 2 m = 1
25.000000 n = 0 m = 2
32.000000 n = 5 m = 0
40.000000 n = 3 m = 1
50.000000 n = 1 m = 2
80.000000 n = 4 m = 1
100.000000 n = 2 m = 2
125.000000 n = 0 m = 3
160.000000 n = 5 m = 1
200.000000 n = 3 m = 2
250.000000 n = 1 m = 3
400.000000 n = 4 m = 2
500.000000 n = 2 m = 3
625.000000 n = 0 m = 4
800.000000 n = 5 m = 2
1000.000000 n = 3 m = 3
1250.000000 n = 1 m = 4
2000.000000 n = 4 m = 3
2500.000000 n = 2 m = 4
3125.000000 n = 0 m = 5
4000.000000 n = 5 m = 3
5000.000000 n = 3 m = 4
6250.000000 n = 1 m = 5
10000.000000 n = 4 m = 4
12500.000000 n = 2 m = 5
20000.000000 n = 5 m = 4
25000.000000 n = 3 m = 5
50000.000000 n = 4 m = 5
100000.000000 n = 5 m = 5