约瑟夫问题的解法

解法一:

         一次将消除的元素进行标记,最后判断元素的个数,如果还剩一个,那么循环结束。

public class YueSefuS {
  public static void main(String args[]){
      YueSefuS yueSe = new YueSefuS();
     
      System.out.println(yueSe.getYueSe(40, 3));
     
     
     }
 
  private int getYueSe(int m,int n){
   int a[] = new int[m];
   //用来标记还有几个活着的
   int count=m;
   //用来标记报数的
   int j=0;
   int i=-1;
   while(count!=0){ 
      i=(i+1)%m;
         if(a[i]==0){
          j++;
         }
    
      if(j==n){
       //标记为1
       a[i]=1;
       j=0;
       count--;
      
      }
    
   }
 
      return i;
  
  }

}

解法二:

使用递归的方法:

public class YueSeFu {
       public static void main(String args[]){
        YueSeFu yueSe = new YueSeFu();
       
        System.out.println(yueSe.getYueSe(40, 3));
       
       
       }
       //m代表多少人,n代表数到几
       public int getYueSe(int m,int n){
         if(m==1){
          return 0;
         }
         else{
          return (getYueSe(m-1,n)+n)%m;
         }
       
       }
}

猜你喜欢

转载自blog.csdn.net/oracle1158/article/details/38731143