第一种方法是简单的java算法问题,第二种c++问题确实纠结
public class Josephus { static void josephus( int[] A,int s, int m ) { int n=A.length; int i, j, k, tmp; if ( m == 0 ) { System.out.println("m = 0是无效的参数!"); return; } for ( i = 0; i < n; i++ ) A[i] = i + 1;/*初始化,执行n次*/ i = s - 1; /*报名起始位置*/ for ( k = n; k > 1; k-- ) { /*逐个出局,执行n-1次*/ if ( i == k ) //当前队列最后一个即为出局者,将i移到0 i = 0; i = ( i + m - 1 ) % k; /*寻找出局位置*/ if ( i != k-1 ) { tmp = A[i]; /*出局者交换到第k-1位置*/ for ( j = i; j < k-1; j++ ) A[j] = A[j+1]; A[k-1] = tmp; } } for ( k = 0; k < n / 2; k++ ) {/*全部逆置, 得到出局序列*/ tmp = A[k]; A[k] = A[n-k-1]; A[n-k-1] = tmp; } for(int v=0; v<A.length; v++) System.out.print(A[v]+" "); } static void josephus2( int[] A,int s, int m ) { int n=A.length; int t=0; for (int i = 2; i <=n; i++) { t = (t + m) % i; } System.out.println("The winner is "+(t+1)); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] list = new int[9]; System.out.println("Josephus problem solution1:"); josephus(list,1,5); System.out.println("\n\nJosephus problem solution2:"); josephus2(list,1,5); } }
#include <stdio.h> int main() { int n, m, i, s = 0; printf ("N M = "); scanf("%d%d", &n, &m); for (i = 2; i <= n; i++) { s = (s + m) % i; } printf ("\nThe winner is %d\n", s+1); }