Thursday, October 30, 2014

Java Simple Pro



Factors.java

public class Factors 
{
public static void main(String[] args) 
{ 
                     long n = Long.parseLong(args[0]);
                     System.out.print("The prime factorization of " + n + " is: ");
 
         for (long i = 2; i*i <= n; i++)
         {
                       while (n % i == 0) 
         {
                System.out.print(i + " "); 
                n = n / i;
            }
        }
                      if (n > 1) 
                          System.out.println(n);
        else       
          System.out.println();
    }
}

Sample.java

public class Sample 
{
public static void main(String[] args) 
{
        int M = Integer.parseInt(args[0]);    
        int N = Integer.parseInt(args[1]);    
                     int[] perm = new int[N];
        for (int i = 0; i < N; i++)
            perm[i] = i;
                     for (int i = 0; i < M; i++) 
       {
                     int r = i + (int) (Math.random() * (N-i));
                     int t = perm[r];
        perm[r] = perm[i];
        perm[i] = t;
        }
                     for (int i = 0; i < M; i++)
         System.out.print(perm[i] + " ");
        System.out.println();
    }
}

CouponCollector.java

public class CouponCollector 
{
 public static void main(String[] args) 
 {
        int N = Integer.parseInt(args[0]);           
         boolean[N];    
        int cardcnt = 0;                     
        int valcnt = 0;                      
        while (valcnt < N) 
           {
            int val = (int) (Math.random() * N);   
            cardcnt++;                             
            if (!found[val]) valcnt++;             
            found[val] = true;                     
           }
                     System.out.println(cardcnt);
    }
}

No comments:

Post a Comment