8

We have an increasing sequence in which each element is consist of even digits only (0, 2, 4, 6, 8). How can we find the nth number in this sequence

Is it possible to find nth number in this sequence in O(1) time.

Sequence: 0, 2, 4, 6, 8, 20, 22, 24, 26, 28, 40, 42, 44, 46, 48, 60, 62, 64, 66, 68, 80, 82, 84, 86, 88, 200, 202 and so on.

Godfather
  • 5,711
  • 5
  • 21
  • 27
  • where n is start form zero or one? – ankush yadav Jun 03 '16 at 11:42
  • 2
    I'm voting to close this question as off-topic because it's a dump of a homework assignment that shows ZERO effort from the OP. – S.L. Barth is on codidact.com Jun 03 '16 at 11:59
  • 3
    Your first stop on the web when looking at this exact *type* problem is the [On-line Encyclopedia of Integer Sequences (OEIS)](https://oeis.org), which has [this to say for the sequence 0, 2, 4, 6, 8, 20, 22, 24, 26, 28, 40, 42](https://oeis.org/search?q=0%2C+2%2C+4%2C+6%2C+8%2C+20%2C+22%2C+24%2C+26%2C+28%2C+40%2C+42&language=english&go=Search). – Lasse V. Karlsen Jun 03 '16 at 12:54

2 Answers2

11

The nth number in this sequence is n in base 5, with the digits doubled.

def base5(n):
    if n == 0: return
    for x in base5(n // 5): yield x
    yield n % 5

def seq(n):
    return int(''.join(str(2 * x) for x in base5(n)) or '0')

for i in xrange(100):
    print i, seq(i)

This runs in O(log n) time. I don't think it's possible to do it in O(1) time.

It can be simplified a bit by combining the doubling of the digits with the generation of the base 5 digits of n:

def seq(n):
    return 10 * seq(n // 5) + (n % 5) * 2 if n else 0
Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
  • @Paul Hankin : Sir may you please help me with how did you solved this sequence ? – Abhishek Tripathi Jun 05 '16 at 10:22
  • @Ram it's not much help to you, but I saw straight away the relationship with numbers in base 5, and from there, writing the code is relatively straightforward. Lasse in the comments above suggested checking the sequence in OEIS -- that'd be a good way to find the pattern if you didn't see it. – Paul Hankin Jun 05 '16 at 11:00
-2
int Code()
{
    k=0;
   for(i=0;i<=10000;i++)
   {
       count=0;
       n=i;
       while(n!=0)
       {
           c=n%10;
           n=n/10;
           if(c%2!=0)
           {
               count=1;
           }
       }
       if(count==0)
       { a[k]=i;
       k++;}
    }
 }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
api_48
  • 1
  • 1