100 people standing in a circle in an order 1 to 100. No. 1 has a sword. He kills the next person (i.e. No. 2) and gives the sword to the next (i.e. No. 3). All people do the same until only 1 survives. Which number survives at the last? There are 100 people starting from 1 to 100.
I want to solve this puzzle using SQL without using any other languages. I have already done it using python. But unable to convert it in sql as a lack of knowledge.
I have the logic with me which I have tried in python. Here using with clause I am trying to assign values but unable to take the power of 2 immediately smaller than N and couldn't able to figure it out, how can i accomodate everything in a single sql without using loop.
Step 1 : For a given value of N, find the “Power of 2” immediately smaller than N. Let’s call it P
Step 2 : Subtract N from (P-1). Lets call it M, i.e, M = (P-1)- N
Step 3 : Multiply M by 2. i.e M*2
Step 4 : Subtract M*2 from P-1. Let’s call it ans, i.e, ans = (P-1) – (M*2)
So, the person with number “ans” will survive till last.
Your help will be much appreciated.
What I have tried:
WITH p(n) AS (
SELECT 1 from dual
SELECT n+1 FROM t WHERE n < 100
SELECT * FROM t;
with RECURSIVE pow(t)(
select power (t,2) where t<n);