/* Birthday written by Keith Fenske Wednesday, 15 May 2002 Copyright (c) 2002 by Keith Fenske. All rights reserved. When you have a group of people, there is a probability that two or more people have the same birthday. This program calculates the minimum size of a group for the probability to reach a certain number. Obviously, the first person has a unique birthday. After we know the first person's birthday, there are 364 remaining days in the year. (We assume that each year has 365 days: no leap years.) The second person has a 364/365 probability of *not* being born on the same day. The third has a 364/365 x 363/365 probability of *not* being born on either of the first two days. And so on. Here is a chart of some results: goal n probability that all birthdays are different 22 0.5243 0.50 23 0.4927 28 0.3455 0.33 29 0.3190 31 0.2695 0.25 32 0.2467 In other words, if you have a group of 23 people (or more), then you have greater than a 50% chance of two people sharing the same birthday. */ import cs1.Keyboard; // import Lewis/Loftus keyboard class // http://duke.csc.villanova.edu/jss/keyboard.html public class Birthday { public static void main(String[] args) { double current; // current probability double goal; // probability that we are looking for int n; // group size System.out.println("\nThis program calculates the smallest group size n"); System.out.println("where the probability that n people do *not* have"); System.out.println("the same birthday is less than a probability given"); System.out.println("by the user."); do { System.out.println("\nPlease type a probability from 0.0 to 1.0"); System.out.println("(or any other number to quit):"); goal = Keyboard.readDouble(); // System.out.println("goal = " + goal); if ((goal >= 0.0) && (goal <= 1.0)) { current = 1.0; // first person has 1.0 probability n = 1; // start with one person while ((current > goal) && (n < 365)) { // System.out.println("current = " + current + " n = " + n); n = n + 1; // add one more person current = current * (365.0 - n + 1.0) / 365.0; } System.out.println("The probability that " + n + " people have different"); System.out.println("birthdays is " + current); } } while ((goal >= 0.0) && (goal <= 1.0)); } // end of main() } // end of class