/**
* Demonstrate Methods Using While
*
* @author (Michael Branicky), 09/20/06, 09/26/07
*/
public class WhileMethods 
{
   // Returns: a random dice roll
   public static int rollDie () {
     return (int) (Math.random()*6.0)+1;
   } 

   public static int rollDieUntilSix() {
     int numberOfRolls, roll;

     roll = rollDie();
     System.out.print(roll+" ");
     numberOfRolls = 1;
     while (roll != 6) {
       roll = rollDie();
       System.out.print(roll+" ");
       numberOfRolls = numberOfRolls + 1;
     }
     System.out.println();
     return (numberOfRolls);
   }

   public static int throwUntilSnakeEyes() {
     int numberOfThrows;  // A throw is rolling two dice
     int roll1, roll2;

     roll1 = rollDie();
     roll2 = rollDie();
     numberOfThrows = 1;
     System.out.print(roll1+" "+roll2+";  ");
     while ((roll1 != 1) || (roll2 != 1)) {
       roll1 = rollDie();
       roll2 = rollDie();
       System.out.print(roll1+" "+roll2+";  ");
       numberOfThrows = numberOfThrows + 1;
     }
     System.out.println();
     return (numberOfThrows);
   }

   // returns true if n>=2 is prime; false, otherwise
   public static boolean isPrime (int n) {
     int i;
     if (n < 2) {      // prime must be >=2
       return false;
     } 
     i = 2;
     // test factors up to, and including, the square root of n
     while (i*i <= n) {
       // if i evenly divides n, n isn't prime
       if (n%i == 0) {
         return false;
       }
       i = i + 1;
     }
     return true;
   } 


   public static void main(String args[])
   {
     int i;
     
     // Test/use the rollDieUntilSix method
     System.out.println("A six took "+rollDieUntilSix()+" rolls.\n");
     System.out.println("A six took "+rollDieUntilSix()+" rolls.\n");

     // Test/use the throwUntilSnakeEyes method
     System.out.println("\"Snake Eyes\" took "+throwUntilSnakeEyes()+" throws.\n");
     System.out.println("\"Snake Eyes\" took "+throwUntilSnakeEyes()+" throws.\n");

     // Test/use the isPrime method
     if (isPrime(2)) { System.out.println("2 is prime"); }
     if (isPrime(4)) { System.out.println("4 is prime"); }
     if (isPrime(36)) { System.out.println("36 is prime"); }
     else { System.out.println("36 is not prime"); }
     if (isPrime(37)) { System.out.println("37 is prime"); }
     else { System.out.println("36 is not prime"); }
     System.out.print("52 is ");
     if (!isPrime(52)) { System.out.print("not "); }
     System.out.println("prime");
     System.out.println();

     // Find the first 100 primes
     System.out.print("First 100 primes:\n");
     i = 2;
     int numFound = 0;
     
     while (numFound < 100) {
       if (isPrime(i)) {
         numFound = numFound + 1;
         if(numFound%10!=0) {
           System.out.print(i+",\t");
         }
         else {
           System.out.println(i);
         }    
       }
       i = i + 1;
     }
     System.out.print("\n");
   }
}
