获得两个随机数(100以内),并放入数组中

public int[] getTwoRandom(){
      int[] t = new int[2];
      Random rand = new Random();
      for(int i=0;i<t.length;i++)
      {
       t[i] = rand.nextInt(100);
      }     
      return t;
    }

 

1、一般算法,连续整数检测法即从m和n中比较小的数开始一次遍历整数,如果有出现可以同时被m和n整除的数,就是最大公约数

//连续整数检测法
    public int getDivisor1(int[] arr){
        int t=0;
        int i1=0,i2=0;
        for(int i=0;i<arr.length;i++){
         i1=arr[0];
         i2=arr[1];
      }
      if(i1>i2){
        t=i2;
      }else{
        t=i1;
      }
      for(int i=t;i>1;i--){
        if((i1%i==0)&&(i2%i==0)){        
            return i;
        }
      }
      return 1;
    }

2、欧几里德算法

   得到一个大小为2的数组,判断两个数的大小

public int getDivisor2(int[] arr){
        int i1=40,i2=50;
        /* for(int i=0;i<arr.length;i++){
         i1=arr[0];
         i2=arr[1];
      } */
      int temp =0;
        if(i1<i2){
            temp=i2;
            i2=i1;
            i1=temp;
        }
      return gcd(i1,i2);
    }

 

(1)、递归方法

public static int gcd(int m,int n){ //使用递归算法实现
    
        if(n==0){
            return m;
        }else{
            return gcd(n,m%n);
        }
    }

(2)、一般循环方法

 

//使用while循环
    public static int gcd1(int m,int n){
        int t = m%n;
        while(t!=0){
            m=n;
            n=t;
            t=m%n;
        }
        return n;
   }

 

posted on 2014-10-12 13:14  一粒麦子777  阅读(5756)  评论(0编辑  收藏  举报