Home > Mobile >  Counting lottery odds - question about the code
Counting lottery odds - question about the code

Time:10-26

I was analyzing the following code concerning Lottery Odds and I have 2 questions:

  • why do we need to set lotteryOdds' value to 1 first (also, is it a usual situation in calculations of this type?)

  • I know the formula used for counting the odds (n*(n-1)...(n-k 1)/(1*2...*k), but if someone explained me how it works in accordance to repeating the "for" loop, I'd appreciate.

    import java.util.Scanner;
    
      public class LotteryOdds {
    
    
          public static void main(String[] args) {
    
          Scanner in = new Scanner(System.in);
    
          System.out.println(" How many numbers do you need to draw? ");
          int k = in.nextInt();
    
          System.out.println(" what is the highest numbers you can do draw? ");
          int n = in.nextInt();
    
          int lotteryOdds = 1;
    
          for (int i = 1; i <= k; i  ) {
              lotteryOdds = lotteryOdds * (n - i   1) / i;
    
              System.out.println("Your odds are 1 in "   lotteryOdds   " . Good luck!");
          }
    
      }
    

    }

CodePudding user response:

The lotteryOdds variable needs to be 1, because if you do 0 * something you will always get 0, so the program will always return 0. As for the loop, lets change the values and go trough the loop: First iteration:

lotteryOdds = 1 * (n - 1 1) / 1 = n / 1

Second iteration:

lotteryOdds = n * ((n - 2 1) / 2) = (n / 1) * ((n - 1) / 2) = n * ((n - 1) / 2) = ((n * (n - 1)) / (1 * 2)

Etc. So when you generalize it you get: (n * (n - 1)...(n - k 1) / (1 * 2 ... * k) just like in the formula above.

  • Related