Thursday, October 30, 2014

Java prime pro



PrimeSieve.java

public class PrimeSieve 
{
 public static void main(String[] args) 
{ 
        int N = Integer.parseInt(args[0]);
                     boolean[] isPrime = new boolean[N + 1];
        for (int i = 2; i <= N; i++) 
        {
            isPrime[i] = true;
        }
                     for (int i = 2; i*i <= N; i++) 
            {
                        if (isPrime[i]) 
            {
                for (int j = i; i*j <= N; j++) 
            {
                    isPrime[i*j] = false;
                }
            }
        }
                      int primes = 0;
        for (int i = 2; i <= N; i++) 
         {
            if (isPrime[i]) primes++;
         }
        System.out.println("The number of primes <= " + N + " is " + primes);
    }
}

SelfAvoidingWalk.java

public class SelfAvoidingWalk 
{
 public static void main(String[] args) 
{
        int N = Integer.parseInt(args[0]);       
        int T = Integer.parseInt(args[1]);       
        int deadEnds = 0;                        
                        for (int t = 0; t < T; t++) 
            {
            boolean[][] a = new boolean[N][N];   
            int x = N/2, y = N/2;                
                         while (x > 0 && x < N-1 && y > 0 && y < N-1)  
            {
            if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1])
             {
                    deadEnds++;
                    break;
                } 
                a[x][y] = true; 
                double r = Math.random(); 
                if      (r < 0.25) { if (!a[x+1][y]) x++; 
                }
                else if (r < 0.50) { if (!a[x-1][y]) x--; 
                }
                else if (r < 0.75) { if (!a[x][y+1]) y++; 
                }
                else if (r < 1.00) { if (!a[x][y-1]) y--; 
                }
            } 
        } 
        System.out.println(100*deadEnds/T + "% dead ends"); 
    } 
} 

RandomSeq.java

public class RandomSeq 
{ 
 public static void main(String[] args) 
{
                        int N = Integer.parseInt(args[0]);
 
       for (int i = 0; i < N; i++) 
            {
            System.out.println(Math.random());
             }
    }
}

No comments:

Post a Comment