Python implementation of the Joseph Ring problem, python implementation of the Joseph Ring
This article describes how to implement the Joseph Ring in Python. We will share this with you for your reference. The details are as follows:
Question:The n numbers 0, 1,..., n-1 are arranged in a circle, and the m number is deleted from the circle each time starting from the number 0. Find the remaining number in the circle.
Defines the f (n, m) function, indicating that the last number after the m number is deleted each time in n numbers (,..., n-1.
Assume that the first number to be deleted is k among n digits, and the n-1 digits left after k is deleted are 0 ~ K-1, k 1 ~ N-1, And the next deletion starts counting from number k 1. The remaining number at the end of the second sequence is the number we requested. So we re-number the remaining n-1 numbers, k 1 number is 0, k 2 number is 1 ,..., 0 number is n-k-1, 1 number is n-k, K-1 number is N-2, Assuming f (n-1, m) = x, n-1 number, each time delete the m number, the remaining number is x, which corresponds to the number (x + m) % n in the original sequence (n number. The recursive relationship can be obtained:
F (n, m) = 0, n = 1
F (n, m) = [f (n-1, m) + m] % n> 1
Python code:
# Coding = utf8''' question: 0, 1,..., n-1 the n numbers are arranged in a circle, and the m number is deleted from the circle each time from the number 0. Find the remaining number in the circle. '''Def Joseph us (n, m): if type (n )! = Type (1) or n <= 0: raise Exception ('n must be an integer (n> 0) ') if n = 1: return 0 else: return (Joseph PHUs (n-1, m) + m) % nif _ name _ = '_ main _': print Joseph (8, 3) print Joseph PHUs (1, 2) print Joseph PHUs (0, 2)