Challenge #7 – The Josephus Problem

3 February 2019 Open Twig Intermediate

In this mythical-historical mathematical problem, where you end up standing can be the difference between life and death. We’ll let Numberphile explain the problem and solution in the following video.


The challenge is to write a twig macro that accepts a single parameter n (an integer representing the total number of people in the circle) and outputs the position in which one must initially stand in the circle in order to be the last person standing and therefore the only survivor.

{% set n = 41 %}

{{ josephus(n) }}    // Outputs 19

Note: an online search will yield various approaches to solving this problem. The challenge here is to come up with your own twig-specific solution using the information provided in the video.


The macro must output an integer as the solution, given the parameter as described above. It should not rely on any plugins and the code will be evaluated based on the following criteria in order of priority:

  1. Originality
  2. Readability
  3. Brevity

The algorithm you use should be based around one of the solutions presented in the video. The code should be readable, concise and non-repetative.


The problem can be solved in twig using either an iterative or a recursive approach. We covered recursion in a previous challenge (#4) and this may be a good opportunity to put your understanding of it to the test.


Submissions will be closed on 19 February 2019 at 22:00:00 CET.

Submit A Solution