I encountered an interview questions which asks you to print the value of 3i * 7j
in increasing order but in optimal way.e.g.
30 * 70 = 1
31 * 70 = 3
30 * 71 = 7
32 * 70 = 9
31 * 71 = 21
33 * 70 = 27
and so on ...
I encountered an interview questions which asks you to print the value of 3i * 7j
in increasing order but in optimal way.e.g.
30 * 70 = 1
31 * 70 = 3
30 * 71 = 7
32 * 70 = 9
31 * 71 = 21
33 * 70 = 27
and so on ...
You could use a heap. Start by inserting the smallest value (3^0 * 7^0
). At each step, print the minimum (this will be the root of your heap), remove it, and add 3 * minimum
and 7 * minimum
to the heap.
This has O(log n)
time complexity.
A(i,j)=3^i * 7^j
when i != 0 and j != 0:
A(i,j)=A(i-1,j-1)*21
when i!=0 and j==0:
A(i,0)=A(i-1,0)*3
when i==0 and j!=0:
A(0,j)=A(0,j-1)*7
when i==0 and j==0:
A(0,0)=1
You can store the them into a 2-D array, such that you can get the former value from it.
the only thing i can think of when you say optimal is to calculate it and save in a table the values. then calculate only the multiplication
long[] threePower = new long[10];
long[] sevenPower = new long[10];
threePower[0] = sevenPower[0] = 1;
for (int i = 1; i < 10; i++)
{
threePower[i] = threePower[i - 1]*3;
sevenPower[i] = sevenPower[i - 1] * 7;
}
and then print the combinations