-4

Consider the We are having {0,2,4,6,8} digits only. Now we have to find the N numbers of a series.

Series : 0,2,4,6,8,20,22,24,26,28,40.....

int start=0;
while(found!=n){

      if(start is not odd)found++;
      start+=2;
}

How can we do that efficiently ?

For Ex N=6  Ans=20
Mureinik
  • 297,002
  • 52
  • 306
  • 350
user6250837
  • 458
  • 2
  • 21

4 Answers4

5

You are trying to make up a number from 5 digits, so this is essentially a base-5 number, just with a quirky set of digits - {0, 2, 4, 6 ,8} instead of {0, 1, 2, 3, 4}. Note that each digit in the required digit set is double the digit in the corresponding index of the base-5 digit set. So, to make a long story short, you could convert N to base 5 and then double the result. E.g., in Java (or C/C++, funnily enough):

int createNumber(int n) {
    int result = 0;
    while (n > 0) {
        result *= 10;
        result += (n % 5);
        n /= 5;
    }
    return result * 2;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Considering 0,2,4,6,8 as 0,1,2,3,4 we can see that you need to calculate the base-5 representation of N, and then replace the digits accordingly. The time complexity will be O(log5(N))

// N stores a value in base 10
   // solution will have digits in an array
   index = 0 ;
   while (N != 0)
   {
      remainder = N % 5 ;
      N = N / 5 ;
      digit[index] = remainder * 2; //0 = 2*0, 2 = 2*1, 4=2*2, etc
      index ++ ;
   }
saby
  • 158
  • 1
  • 1
  • 7
0

Detailed Explanation:

Convert N->N-1 to exclude 0.

Let A = {0, 2, 4, 6, 8}

Let's count how many numbers have k, (k > 1) digits and all their digits belong to set {0, 2, 4, 6, 8}. First digits can be chosen in 4 ways, all other digits in 5 ways, so in total, 4*pow(5, k-1). Which means, if m = ceil(log5(N)), then Nth number in series has m digits.

Now, if the first digit in base-5 representation of N equals i, (1 <= i <= 4) then first digit in our answer is A[i]. Same holds second digit and so on.

So in your algorithms you need to present N in base-5, e.g. N=abcde.., where each of a,b,c is in range [0..4] and ur answer will be a result of mapping each of a -> A[a]

Yerken
  • 1,944
  • 1
  • 14
  • 18
-2

You could use a permutation algorithm and then sort it in ascending order. Using this, even if you add more digits to your sample space, the series would still work. See- https://en.wikipedia.org/wiki/Heap's_algorithm

Note: Using a permutation for something so simple is overboard. But if you are looking for an algorithm which can take more digits and form a series, then permutation is a good way to use.

leoOrion
  • 1,833
  • 2
  • 26
  • 52