Odd-Even elimination

The integers 1 through 12345 (inclusive) are written in a row in ascending order. You and your friend take turns removing numbers according to the following rules:

  • Step 1: You remove numbers from all odd positions (i.e. 1, 3, 5, ..., 12345).
  • Step 2: Your friend removes numbers from all even positions (i.e. 4, 8, ... because 2 is now in position #1 and 6 is in position #3, and so on).
  • Step 3: If there is more than one number remaining on the list, repeat the steps above.

What is the last number remaining after completing these steps?


Note:
The diagram to the right illustrates the case for a list of numbers 1 to 8.


The answer is 5462.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

22 solutions

Arjen Vreugdenhil
Jan 10, 2018

Binary number approach

Subtract 1 from all numbers and positions, and write them in binary notation. (Thus, 000 is at position 0, 001 at position 1, and so on.)

After the first step, only the numbers ending in 1 survive, and their new position number is obtained by removing the 1. (Thus, 001 at position 0, 011 at position 1, etc.)

After the second step, only the positions ending in 0 survive, which are all numbers ending in 01, and their new position is obtained by removing 01. (Thus, 001 at position 0, 101 at position 1, 1001 at position 2, etc.) After the n n th step, the surviving number in position a a is a 010101 n digits \overline{a \underbrace{\dots 010101}_{n\ \text{digits}}} .

Since 2 13 < 12345 < 2 14 2^{13} < 12345 < 2^{14} , we can perform 14 steps before we end up with 0101010101010 1 2 = 546 1 10 01010101010101_2 = 5461_{10} at position 0. Adding back in the 1 we subtracted, the answer is therefore 5462 \boxed{5462} .


By way of generalization, any binary number following the patter x = 10101 10 1 2 x = 10101\dots101_2 satisfies the equation 4 x + 1 x = 4 n x = 4 n 1 3 4x + 1 - x = 4^n\ \ \ \ \ \therefore\ \ \ \ \ \ x = \frac{4^n-1}3 for some integer n n . Thus, with n = 6 n = 6 we obtain x = ( 4 6 1 ) / 3 = 1365 x = (4^6 - 1)/3 = 1365 , and with n = 7 n = 7 we find x = 5461 x = 5461 , etc.

Therefore the general solution to this problem is the largest available number that may be written in the form 1 3 ( 4 n 1 ) + 1 \tfrac13(4^n - 1) + 1 , or 1 3 ( 4 n + 2 ) \tfrac13(4^n + 2) .


Alternative approach

Divide the sequence into blocks of four numbers. Thus, block # k k consists of the numbers 4 k 3 , , 4 k 4k-3, \dots, 4k .

Of each block, only the second number survives, i.e. 4 k 2 4k - 2 .

After steps 1 and 2, the surviving number of the k k th original block is now the k k th number. Therefore, if a number has position k n k_n after n n steps, its position after n 1 n-1 steps must satisfy k n 1 = 4 k n 2 k_{n-1} = 4k_n - 2 . Definition x a : = k n a x_a := k_{n-a} , this becomes x a + 1 = 4 x a 2. x_{a+1} = 4x_a - 2.

At the end of the process ( n n repetitions) we have one number left, in the first position, i.e. k n = x 0 = 1 k_n = x_0 = 1 . Work backward to find the original position k 0 = x n k_0 = x_n : a 0 1 2 3 4 5 6 7 8 x a 1 2 6 22 86 342 1366 5462 21 846 \begin{array}{ccccccccc} a & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ \hline x_a & 1 & 2 & 6 & 22 & 86 & 342 & 1366 & 5462 & 21\:846 \end{array}

Since we started with numbers up to 12 345 12\:345 , the process must end after seven steps at k 0 = k n 7 = 5462 k_0 = k_{n - 7} = \boxed{5462} .

Or , to generalize further, we can find an explicit expression for x a x_a . The recursion x a + 1 = 4 x a 2 x_{a+1} = 4x_a - 2 clearly describes exponential growth, but we must account for the term 2 -2 . The trick is to rewrite it as x a + 1 2 3 = 4 ( x a 2 3 ) . x_{a+1} - \tfrac23 = 4(x_a - \tfrac23). The solution of this recursion is x a 2 3 = ( x 0 2 3 ) 4 a , x_a - \tfrac23 = (x_0 - \tfrac23)\cdot 4^a, or x a = 4 a + 2 3 . x_a = \frac{4^a + 2}3. Substituting a = 7 a = 7 gives indeed x 7 = 4 7 + 2 3 = 16 384 + 2 3 = 5462 . x_7 = \frac{4^7 + 2}3 = \frac{16\:384 + 2}3 = \boxed{5462}.

In general, if the original series contains the numbers 1 , , N 1, \dots, N , then the remaining number is 4 log 4 ( 3 N 2 ) + 2 3 . \frac{4^{\lfloor \log_4 (3N-2) \rfloor} + 2}3.

Excellent approach ....

Ossama Ismail - 3 years, 5 months ago

Please check out my solution... regards

Ossama Ismail - 3 years, 5 months ago
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include<cstdio>

using namespace std;

int main()
{
    int a=1, b=1;

    while(1)
    {
        if(a+b>12345)
            break;
        if(a+2*b>12345)
            break;
        a+=b;
        b*=4;
    }
    printf("%d\n", a);

    return 0;
} 

I used Dev C++ to solve this ^-^

Adolf Hitler - 3 years, 4 months ago

impressive

Coco Tsai - 3 years, 4 months ago

And that's why I love pyhon:

1
2
3
4
5
6
allnum = range(1,12346)
while len(allnum)>1:
    allnum = allnum[1:len(allnum):2]
    if len(allnum) > 1:
        allnum = allnum[0:len(allnum):2]
print allnum[0] 

Roman Sologub - 3 years, 4 months ago

Log in to reply

As I read the instruction, steps 1 & 2 will always occur together, with the only decision in step 3. Fortunately, step 2 always leaves the 1st element of the array anyway. So the code in my loop was simply a=(a[1::2])[0::2].

Interestingly, Python3 is smart enough to see that each such iteration simply filters the original range. If you print out the range variable at each step, it will return this sequence:

range(1, 12346)

range(2, 12346, 4)

range(6, 12350, 16)

range(22, 12374, 64)

range(86, 12374, 256)

range(342, 12630, 1024)

range(1366, 13654, 4096)

range(5462, 13654, 16384)

range(21846, 21846, 65536)

…

Jerry Barrington - 3 years, 4 months ago

Log in to reply

Yep, I later saw you solution, no need for if. The smart behaviour of range is really impressing, wow!

Roman Sologub - 3 years, 4 months ago

Can I get the solution in C language??!!

Sravan Kumar - 3 years, 4 months ago

Log in to reply

Sorry, I haven't understood your question.

Muhammad Rasel Parvej - 3 years, 4 months ago

In the C language, change the first line to #include<stdio.h> and remove the using namespac std; line. Then it should work.

Arjen Vreugdenhil - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Ossama Ismail
Jan 11, 2018

The starting number (head) of the 1st list is 1, where the list = [ 1 , 2 , 3 , 4 , . . . , 12345 ] The starting number (head) of the 2nd list is 2, where the list = [ 2 , 4 , 6 , 8 , . . . , 12344 ] The starting number (head) of the 3rd list is 6, where the list = [ 6 , 10 , 14 , . . . , 12344 ] \begin{aligned} \text {The starting number (head) of the 1st list is 1, where the list} &= [ 1,2,3,4, ..., 12345] \\ \text {The starting number (head) of the 2nd list is 2, where the list} &= [ 2,4,6,8,..., 12344] \\ \text {The starting number (head) of the 3rd list is 6, where the list} &= [ 6,10,14,..., 12344] \\ \\ \end{aligned} or in genral the value of head of the list after K iterations will be h e a d ( K ) = ( 4 K + 2 ) 3 . . . . . . . ( 1 ) \text {or in genral the value of head of the list after K iterations will be } head(K) = \dfrac{(4^K + 2)}{3} ....... (1)

A list with h e a d ( n ) > 12345 head(n) \gt 12345 will be empty this \implies that the answer is max ( h e a d ( n ) ) (head(n)) where h e a d ( n ) 12345 head(n) \le12345

Let N be the value of n that satisfies equation, Let S to be the upper bound of the range s = 12345 in this case \displaystyle \text {Let N be the value of n that satisfies equation,} \\ \text {Let S to be the upper bound of the range} s = 12345 \ \ \text{in this case}

Solving equation (1) gives N = l o g 4 ( 3 S 2 ) N = {\lfloor log_4(3S - 2) \rfloor }

the general answer is h e a d = ( 4 N + 2 ) 3 head = \Large{\lfloor \frac {(4^N + 2)}{ 3 } \rfloor}

In this problem S = 12345 N = 7 S = 12345 \implies N = 7

h ( N ) = ( 4 N + 2 ) 3 = ( 4 7 + 2 ) 3 = ( 16384 + 2 ) 3 = 16386 3 = 5462 \begin{aligned} h(N) &= \dfrac{(4 ^N + 2) }{ 3 } = \dfrac{(4 ^ 7+ 2)} {3} = \dfrac{ ( 16384 + 2) }{3} = \dfrac{16386}{ 3}\\ \\ &= \Large 5462 \\ \end{aligned}

This solution is fine-- one thing is missing, and that is the derivation of the equation head ( K ) = 4 K + 2 3 . \text{head}(K) = \frac{4^K + 2}3.

Arjen Vreugdenhil - 3 years, 5 months ago

Log in to reply

Just geometric sum and some algebra. It is fully derived over at my solution.

Robert DeLisle - 3 years, 4 months ago

Log in to reply

I don't see where your eqn. (1) comes from.

Arjen Vreugdenhil - 3 years, 4 months ago

Log in to reply

@Arjen Vreugdenhil Not sure which you mean, as there is not "(1)" type reference used in my solution. . Are you still referring to this Ismail solution. I was referring to my posted solution elsewhere that I think explains Ismail's (1) adequately, and uses a somewhat simpler explanation for it without the "head' business. You are quite right, Ismail just throws that it there, as if the fact that it fits the first three entries shown insures that late entries must follow the pattern (and in this case, they do) without proof.

Robert DeLisle - 3 years, 4 months ago

Log in to reply

@Robert DeLisle I see what you mean. Yes, I thought that you were talking about this post. You are right that it is "just geometric sum and some algebra". But that is precisely the interesting part of the problem: how do you know what sum it is, and how do you do the algebra in a clever way? Your solution gives a detailed account of it, but Ossama Ismail's doesn't.

Arjen Vreugdenhil - 3 years, 4 months ago

Log in to reply

@Arjen Vreugdenhil Thank you. Couldn't spare me an upvote while you were there?

Robert DeLisle - 3 years, 4 months ago

Not sure why the this list starts with 6 not two.

alex K - 3 years, 4 months ago

Log in to reply

Actually it starts at 1 with 4 0 + 2 3 = 1 \frac {4^0 + 2 } {3} = 1 . The solution is fully general and works even with a list with one number.

Robert DeLisle - 3 years, 4 months ago

you say that head(N) is the maximum solution it means that the solution cannot be bigger than this particular value but why then you concluded it is the right one , you should know that the upper bound also get smaller with iterations , right ? So it is possible that we end up having a smaller number than head(N) in case the upper bound gets actually smaller than this particular value(S gets smaller and head(n) gets bigger ) , what i want to say is that the S which you plugged(12345) depend also on K the number of iterations so you cannot just fix it and then apply your formula , you should take on consideration that it is changing with iterations .Can you justify the affirmation you said after the implication symbol ? for me it should be (head(n) < S(n) ) where S(n) is the upper bound at an iteration n ) Thank you ,please correct me if i'm wrong .(Ohh and btw not sure the the list is fine )

Ziyad BENKHADAJ - 3 years, 4 months ago
Stewart Gordon
Jan 24, 2018

Write the numbers in base 4. Initially: 1, 2, 3, 10, 11, 12, 13, 20,...

After removing the numbers in odd position: 2, 10, 12, 20, 22, 30, 32, 100,...

After removing the numbers now in even position: 2, 12, 22, 32, 102, 112, 122, 132,...

We have left the numbers ending with 2.

After removing the numbers now in odd position: 12, 32, 112, 132, 212, 232, 312, 332,...

After removing the numbers now in even position: 12, 112, 212, 312, 1012, 1112, 1212, 1312,...

All numbers ending with 12.

Continuing in this way, it's obvious that the smallest remaining number at each cycle follows the pattern 2, 12, 112, 1112,....

The answer is thus the largest number in this sequence not greater than 12345 decimal, namely 111111 2 4 = 5462 10 1111112_4 = \boxed{5462}_{10} .

Nice approach. Excellent observation !!

Ossama Ismail - 3 years, 4 months ago

That's excellent. better math than I used. I did it the hard way starting from the observation that each new position is given by CEILING(p/2), leading to a summation of powers of 4 and a formula, but this clearly shows the powers of four at the core of the problem.

It is annoying how many brute force programs have been posted, some crude,some very clever near one liners, all missing the point, from people who don't care to actually solve the problem.

Robert DeLisle - 3 years, 4 months ago
Victor Dumbrava
Jan 23, 2018

A recursive Python solution (a bit simpler than the others), which uses Extended Slicing :

1
2
f = lambda l, i = 1: f(l[i :: 2], 0 ** i) if l[1:] else l[0]
print(f(list(range(1, 12346))))

Prints the correct result, 5462 . Test it online!

Yep, the functional style is the best.

1
2
3
4
Prelude> let removeEvens xs = [v|(v, i) <- zip xs [1..], odd i]
Prelude> let removeOdds xs = [v|(v, i) <- zip xs [1..], even i]
Prelude> (head . head) $ filter (\xs -> length xs <= 1) $ iterate (removeEvens. removeOdds) [1..12345]
5462

Agnishom Chattopadhyay - 3 years, 4 months ago

Log in to reply

Actually using math to solve the problem is the best.

For example, (In Excel VBA, for convenience not preference, the input 12345, and output 5462 appear in textboxes on a form.)

Private Function LastNumber(n As Long) As Long

  LastNumber = ( 4  ^  ( Int( Log(3 * CDbl(n) - 2 ) / Log(4) )) + 2) / 3

End Function

Robert DeLisle - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Paul Sinnett
Jan 22, 2018

Each step the count of the numbers is halved (rounding down on odd turns and up on even turns.) On even turns, the lowest number remains the same (because it isn't removed.) On odd turns, the lowest number becomes the next number (the lowest number + the step.) On each turn the step between the consecutive values doubles.

turn count lowest step
- 12345 1 1
1 6172 2 2
2 3086 2 4
3 1543 6 8
4 772 6 16
5 386 22 32
6 193 22 64
7 96 86 128
8 48 86 256
9 24 342 512
10 12 342 1024
11 6 1366 2048
12 3 1366 4096
13 1 5462 -
Darwin Kim
Jan 27, 2018

If you don't want to do math, make a computer do it for you.

1
2
3
4
5
6
7
a = list(range(1, 12346)) # produces a list of integers between 1 and 12345

while len(a) > 1:
    del a[0::2] # deletes elements in steps of 2 starting from index 0
    del a[1::2] # deletes elements in steps of 2 starting from index 1

print(a) # output is [5462]

Haha, this is a surprisingly short code. This is one of my favorite things about python.

Agnishom Chattopadhyay - 3 years, 4 months ago

Log in to reply

Here is my program:

Private Sub cmdDoIt_Click()

txtLastNumber = (4 ^ (Int(Log(3 * CDbl(txtListLength) - 2) / Log(4))) + 2) / 3

End Sub

surprisingly short code, and it doesn't use more time and memory as the list gets longer either. That's one of the things I like about mathematics.

Robert DeLisle - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Aashita Shyam
Jan 27, 2018

After the first 2 steps, the remaining numbers are:

2, 6, 10, 14, 18, 22, 26, 30, ... ( the difference between the numbers is 4)

After 2 more steps the numbers remaining are:

6, 22, 38, 50, ... ( the difference between these numbers is 4x4= 16)

After the next 2 steps, we get:

22, 86, 150,...( the difference is 16x4= 64)

After 2 more steps, we get:

86, 342, 598,... ( difference of 64x4=256)

342, 1366, 2390,... (difference is 256x4= 1024)

1366, 5462, 9558 (difference 1024x4=4096)

The number after 9558 exceeds 12345. ( 9558+4096=13654)

In the next step, the numbers in the odd positions have to be removed. Hence, the answer is 5462

Chew Zeh Yang
Jan 26, 2018

I am not good in mathematics so this is my approach programmatically:

Array starts as [ i ] where i spans from 1 to 12345 First Value: F=1 Spacing: S=1 [1,2,3,......]

Removing odd index causes second value to get to index of first and spacing doubled

F=2, S=2, array=[2,4,6,8......]

Removing even numbers doesn't change First Value while doubling the spacing

F=2, S=4, array=[2,6,10,14......]

Combining the 2 operations above, we know that after each round of taking away odd then even indexes:

F=F+S as value from second index replaces the first

S=S*4 as each operation to remove odd and even index doubles the spaces between the numbers in the array

Starting from F=1,S=1:

F=1,S=1

F=2, S=4

F=6, S=16

F=22, S=64

F=86, S=256

F=342, S=1024

F=1366, S=4096

F=5462, S=8192 <--- Answer

F=13654,S=32768

A short Python3 program that executes the algorithm :

1
2
3
4
5
l = list(range(1, 12346))
while len(l) > 1:
    l = l[1::2]
    l = l[::2]
print(l)

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Even shorter and much faster code can be seen in my posted solution.

Robert DeLisle - 3 years, 4 months ago
Jam M
Jan 25, 2018
  • If n N n \in \mathbb{N} , then the number of steps required to find the winning number is m m , where 2 m 1 < n < 2 m 2^{m-1} < n < 2^m .
  • After Step i is performed, the remaining numbers are of the form 2 i 1 x + 4 k i + 2 3 2^{i-1}x + \frac{4^{k_i} + 2}{3} , where x N { 0 } x \in \mathbb{N} \cup \{0\} and k i = log 4 ( 3. 2 i 2 ) k_i = \lfloor \log_4(3.2^i - 2) \rfloor
  • The winning number can be found when i = m i = m and x = 0 x = 0 , and that number is 4 k m + 2 3 \frac{4^{k_m} + 2}{3}
  • Now if n = 12345 n = 12345 , note that 2 13 < n < 2 14 2^{13} < n < 2^{14} so that m = 14 m = 14 and k m = 7 k_m = 7 . Therefore, the winning number is 4 7 + 2 3 = 5462 \frac{4^7 + 2}{3} = 5462
Queijo Silva
Jan 25, 2018

Here is my solution, with basic Python 3 functions. The following code could be written in a more pythonic way, but I will keep it simple for all the begginers out there.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
num = list(range(1, 12346))


def t(n):
    do = []
    de = []
    for k in range(0, len(n), 2):
        do.extend([k])
    for i in reversed(do):
        del(n[i])
    for l in range(1, len(n), 2):
        de.extend([l])
    for j in reversed(de):
        del(n[j])


while len(num)!=1:
    t(num)
print(num)

Can I get the solution in C language??!!

Sravan Kumar - 3 years, 4 months ago

Log in to reply

Try getting the solution in mathematics first.

Then you can get a really short program, that doesn't take more effort and memory as the list gets longer as well.

For example, (In Excel VBA, for convenience not preference, the input 12345, and output 5462 appear in textboxes on a form.)

Private Function LastNumber(n As Long) As Long

  LastNumber = ( 4  ^  ( Int( Log(3 * CDbl(n) - 2 ) / Log(4) )) + 2) / 3

End Function

Robert DeLisle - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Andrew Leonard
Jan 24, 2018

I cheated a little lol. I used c++. Try it here (https://www.onlinegdb.com/online c++ compiler), replace everything already in the box:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
\#include <stdio.h>

\#define MAX 12345

int main() {

    int myArr[MAX];

    for (int i = 1; i <= MAX; i++) {
        myArr[i-1] = i;
    }

    int lastNumFlipped = 1;
    bool workLeft = true;
    bool killOdd = true;
    while (workLeft) {
        workLeft = false;
        bool odd = true;

        for (int i = 0; i < MAX; i++) {

            if (myArr[i] != 0) {
                workLeft = true;

                if (odd && killOdd) {
                    lastNumFlipped = myArr[i];
                    myArr[i] = 0;
                }
                if (!odd && !killOdd) {
                    lastNumFlipped = myArr[i];
                    myArr[i] = 0;
                }

            odd = !odd;    
            }
        }
        killOdd = !killOdd;
    }

    printf("Last Num Left: %i\n", lastNumFlipped);
    return 0;
} 

Can i get the solution in C languauge??!!

Sravan Kumar - 3 years, 4 months ago

If one doesn't cheat the result can be a short brutally efficient subroutine that does not need more cycles and memory as the list gets longer. with the list length as a parameter not hard-coded.

For example, (In Excel VBA, for convenience not preference, the input 12345, and output 5462 appear in textboxes on a form.)

Private Function LastNumber(n As Long) As Long

  LastNumber = ( 4  ^  ( Int( Log(3 * CDbl(n) - 2 ) / Log(4) )) + 2) / 3

End Function

Robert DeLisle - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Meneghin Mauro
Jan 23, 2018

after 2 turns (that is step1 and step2), a sort of compression is performed: m ( x ) = x / 4 + 1 / 2 m(x)=x/4+1/2 we can ignore the decimal results, for example after the first 2 turns m m maps 2+4q into q

compounding m, I can write m ( k ) ( x ) = m ( . . . m ( x ) ) m^{(k)}(x) = m(...m(x)) (k-times)

I found m ( k ) ( x ) = i / 4 k + 4 k 1 3 2 2 k 1 m^{(k)}(x) = i/4^k + \frac{4^k-1}{3*2^{2k-1}}

l o g 4 ( 12345 ) = 6.7... log_{4}(12345)=6.7... so I expect after applying m 6 m^6 to find at most 3 integer remaining values, solution of m ( 6 ) ( x ) = 1 , 2 , 3 m^{(6)}(x) = 1, 2, 3

because step 1 has to be performed the solution has to be the second (unless the second value is bigger than 12345)

m ( 6 ) ( x ) = 2 m^{(6)}(x)=2

x = ( 2 4 6 1 3 2 2 6 1 ) 4 6 = 5462 x=(2-\frac{4^6-1}{3*2^{2*6-1}})*4^6=5462 that is a valid solution being less then 12345

Pratik Sapre
Jan 23, 2018
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
n=12345

a<-seq(1,n,1)

it=0

while(length(a)>1)
{
  remove=seq(1+(it%%2),length(a),2)
  a=a[-remove]
  it=it+1
}

print(a[1]) 

What language is this in? I am guessing R

Agnishom Chattopadhyay - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
José A. Diaz
Jan 22, 2018

My python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def main(n):
    l = list(range(1,n))
    while True:
        l = l[1::2] 
        l = l[0::2]
        if len(l)==1:
            break
    return l

if __name__ == '__main__':
    print(main(12345))

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Dan Wheatley
Jan 22, 2018

in Javascript (ES6)

let arr = new Array(12345).fill(0).map((d,i) => i+1 );
while (arr.length > 1) {
  arr = arr
    .filter((d,i) => (i+1) % 2 === 0)
    .filter((d,i) => (i+1) % 2 !== 0);
}
console.log(arr[0]);

Short and sweet. I could run it in my browser.

Agnishom Chattopadhyay - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def remove_indexed(l, c):
    y = []
    for k,i in enumerate(l):
        if c%2:
            if not k%2:
                y.append(l[k])
        else:
            if k%2:
                y.append(l[k])  
    l = [item for item in l if item not in y]
    return l, c
#---------------------------------------------------
low_val = 1
high_val = 12345 
list_ = [x for x in range(low_val,high_val+1)]   
count = 1 # alternate between odd and even, start with odd
while len(list_) > 1:
    list_, count = remove_indexed(list_, count)
    count += 1
    if len(list_) == 1:
        print list_[0]

1
5462

Good job. By the way, I think that there is a built in way to do remove indexed..

Agnishom Chattopadhyay - 3 years, 4 months ago

Log in to reply

There is also a way to make it a single expression. Mathematics.

Robert DeLisle - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago
Javier Álvarez
Jan 28, 2018

At the beginning, it's clear that every number equals it's position.

After the first step, only even numbers remain, and it can easily be seen that now every number equals twice it's position, satisfying the equation x = 2 n x = 2n , where x equals the number and n equals the new position.

After the second step, every number in an even position is eliminated. If we write a few of the numbers remaining: 2 , 6 , 10 , 14 , 18 , 22 , . . . 2, 6, 10, 14, 18, 22, ... , we can see they produce an arithmetic sequence with difference(d) 4, and that x 2 2 ( m o d 4 ) x \equiv 2 \equiv -2 \pmod{4} , such that now x = 4 n 2 x = 4n - 2 , where n is the new position.

If we do the first step (so that this is the third step) again, we'll eliminate numbers in odd positions, and as odd positions occur every two number, and before d = 4, now d will become 8, and the sequence will look like these: 6 , 14 , 22 , 30 , 38 , 46 , 54 , . . . 6, 14, 22, 30, 38, 46, 54, ... and we can see that now, x = 8 n 2 x = 8n - 2 . We can continue doing this, and finding a formula for x after each step, and find a pattern in the formulas that will lead us to a generalization:

4^{th} step: 6 , 22 , 38 , 54 , 70 , . . . 6, 22, 38, 54, 70, ... . Formula: x = 16 n 10 x = 16n - 10 5^{th} step: 22 , 54 , 86 , 118 , 150 , . . . 22, 54, 86, 118, 150, ... . Formula: x = 32 n 10 x = 32n - 10 6^{th} step: 22 , 86 , 150 , 214 , 278 , . . . 22, 86, 150, 214, 278, ... Formula: x = 64 n 42 x = 64n - 42

Now, I hope it'll be easy to verify, that the general formula is (for s 2 s \geq 2 ): x = 2 s n i = 1 s 2 2 2 i 1 x = 2^sn - \sum_{i=1}^{\left \lfloor{\frac{s}{2}}\right \rfloor} 2^{2i-1} , where s equals the step, and n the position.

If someone can find a better general formula, please write it in the comments.

Since the difference in an arithmetic sequence with the remaining numbers (in order) after step s equals 2 s 2^s , and 2 1 3 < 12345 < 2 1 4 2^13 < 12345 < 2^14 , we should check, with the general formula, n = 1 and s = 13 or s = 14. These give respectively 5462 and 5462, because in s = 14 we eliminate numbers in even positions, and 5462, at s = 13 , is in an odd position. If we plug in n = 2, for each of them, we get 13654 and 21846, both bigger than 12345, so we can be sure that the last "survivor" from 1 to 12345 is:

5462 \boxed{5462}

Footnote: I know this is far from being a rigorous solution, but actually i'm not very good at writing solutions, so that if I were to try and prove this way of solving the problem, the solution would become large and difficult to read. I will appreciate if you could give me advice on how to write good and clean solutions down here in the comments.

Consider that new position is always CEILING(position/2) and that the last number sitting alone in position 1 has a unique regression back to an even number in its original position on the initial list.

I finally completed my published solution that (at the moment) comes up immediately after this one.

The solution is L(n) = (4^m + 2 ) / 3 where m = FLOOR ( ln(3n-2) / ln(4) )

The accompanying proof is as simple as possible, and sufficiently rigorous, working entirely from the forced regression path from 1 back to 5462, or for that matter a list of any length whatever starting with 1. (It even works with the degenerate case of a list of just one number.)

I hope this solution is the kind of clean solution you were looking for.

Robert DeLisle - 3 years, 4 months ago
Robert DeLisle
Jan 27, 2018

Here is mathematical solution to the problem and an implementation in program code.

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

SOLUTION

There is a definite sequence of "last numbers". The solution is the greatest "last number" less than the greatest number on the list.

The last number for any list 1..n is given by:

This can be established as follows:

The key fact is that next position from any given position, p, is N ( p ) = p 2 N(p) = \lceil { \frac{p}{2} \rceil } (least integer greater than p/2)

The function N ( ) N() is strictly decreasing until N ( p ) = 1 N(p) = 1 when N ( 1 ) = 1 N(1) = 1 . Thus every number not eliminated by parity will eventually reach position 1 when it will be either the last number or be eliminated on the next odd eliminating step. While it is true that N ( 2 k ) = N ( 2 k 1 ) N(2k) = N(2k-1) it is not a problem because either 2 k 2k or 2 k 1 2k-1 will have been eliminated on parity, to bring the surviving number uniquely to the new position.

What is of interest here is the inverse of N ( ) N() which is not a function. N ( ) N() . Any given position p can only come from one of two prior positions, 2p or 2p-1. The choice of precursor is entirely forced by the type of step, i.e. if the previous step eliminated odd positions, the precursor must be 2p, and if eliminating even positions must be 2p-1.

The last number will be in position 1, the only position remaining. If the current step is odd, then the previous position must have been 1 (not eliminated on an even eliminating step). If the current step is even, then the previous position must have been 2 (not eliminated on an odd eliminating step).

With that logic in hand, the full sequence of last numbers, L m { L_m } can be generated uniquely starting from 1 on an odd eliminating step.

The difference between successive odd steps increases by a factor of 4 can be seen by examining the value of N ( p ) N(p) across successive odd eliminating steps as follows:

The solution to the problem is the greatest L m { L_m } that is less than the highest position in the initial list (since the last number must be on the list in the first place). We can disregard the intermediate odd numbers in the sequence above because they are all eliminated on the first step.

The sums of powers of 4, can be calculated directly using the formula for geometric sums.

From that a general solution is expressed by

The value of m can be obtained directly as follows.

Taking the base 4 logarithm With the value of l o g 4 ( 3 n 2 3 ) log_4 ( \frac{3n - 2}{3 }) between two consecutive integers, and a change of base, it follows that

Which completes the derivation of the function L ( n ) L(n) given at the top of the page.

The value marked in red 5462 is the value of L ( 12345 ) L(12345) and the solution to the given problem.

In the example given with the problem, we see that L ( 8 ) = 6 L(8) = 6 , since L 2 { L_{2} } = 6 < 8 and L 3 { L_{3} } = 22 > 8.

SOFTWARE IMPLEMENTATION

Using the math the resulting code uses fixed resources in both instructions executed and memory used (both minimal without any arrays nor recursion stack ) regardless of the length of the list This is an improvement over the brute force approach that literally performs the elimination step process, both as use of the problem as math exercise and as a programming exercise.

Below is the solution implemented as program code { In Excel VBA for convenience not preference ).

This subroutine implements the solution in the mathematical form derived above

These subroutines implement the solution optimized by the use of right shift pseudo-division to obtain the exponent of 4.

Using a User Form container with a command button.

The code above is executed

Curious how this method starts on the CEILING and ends up on the FLOOR.

My favorite solution so far from a pure math standpoint is the one from Stewart Gordon using base 4, Elegant and without all the mess.

There is a subtle difference between getting the answer and solving the problem.

This is a proof and it produces a direct computation of a solution for a list of any length (even 1) that can be readily incorporated into an efficient computer implementation.

It is not a program that uses the crudest possible brute force procedure (some very explicit, not to say tedious, others elegant near one liners) that increases in effort and memory consumption as n increases without out limit, and might even have a bug, but "hit the jackpot" on this particular case. Slick code, not so slick code, but it is still proof left to the reader.

The solution has now also been implemented in code. Solution first, implementation later.

This particular problem may not be of much inherent importance, but the approach, the rigor, and possibly gaining an improved insight into the underlying mathematics is important.

I thank Ossama Ismail for contributing it. It has been an interesting exercise in applying some mathematics and then using the result as a programming exercise. The more I looked at it the more interesting aspects of it I found The question itself may be inconsequential, but the value of the problem lies in those two things, and not merely getting an answer.

Robert DeLisle - 3 years, 4 months ago
Bo Fu
Jan 26, 2018
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
%Matlab code

List=1:12345;
loop=1;
while (length(List)>1);
    if mod(loop,2)==1;
        index=1:2:length(List);
    else;
        index=2:2:length(List);
    end;
    List(index)=[];
    loop=loop+1;
end 

Eser Gül
Jan 25, 2018

Another python code

a = list(range(1,12346))
b = []
c=[]

while len(a)>1:
    i=0
    j=0
    for n in a:
        if j%2==1:
            b.append(n)
        j+=1

    for n in b:
        if i%2==0:
            c.append(n)
        i+=1        
    a = c
    b=[]
    c=[]


print(a)

Nice, unlike the other solutions, you have actually spelt out the details.

Agnishom Chattopadhyay - 3 years, 4 months ago

THOUGHTS ABOUT SOLUTION WITH CODE

There is such a thing as getting the answer without solving the problem. Emulating the described steps as a brute force "solution" in code is an example.

Applying the mathematical result and some programming technique produces code that uses minimal resources in both time and space (without arrays or recursion stack) that are fixed regardless of list length, and can be optimized by replacing floating point calculations with pure fixed point operations. This lends some depth to the programming side of the solution. The brute force step emulation examples regardless of number of lines of code used all negate the value of the problem both as a math exercise and a programming exercise. That is the objection to most if not all of the program code "solutions".

Robert DeLisle - 3 years, 4 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...