Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 2 (for True Epub)
Назад: 8:
Дальше: 10:

Chapter 9

These are the solutions to the .

  1. Here’s one way to use random sampling to determine the ratio of evens to odds:

     import​ ​random
     
     array = []
     number_of_integers = 1000001
     
     
     for​ i ​in​ range(number_of_integers):
      array.append(i)
     
     random.shuffle(array)
     
     number_of_evens = 0
     number_of_odds = 0
     
     random_sample_size = 500
     
     for​ _ ​in​ range(random_sample_size):
      random_index = random.randint(0, number_of_integers - 1)
     if​ array[random_index] % 2 == 0:
      number_of_evens += 1
     else​:
      number_of_odds += 1
     
     percentage_of_evens = (number_of_evens / random_sample_size) * 100
     percentage_of_odds = (number_of_odds / random_sample_size) * 100
     
     print​([percentage_of_evens, percentage_of_odds])
  2. If The Formula—even once—produces a result that isn’t 1, then we know for certain that N is composite.

  3. Each time I run The Formula on a prime number, there’s no more than a 50 percent chance that I’ll get a result of 1. Therefore, each time I run the formula it’s akin to flipping a coin. Getting a 1 four times is like a coin landing on heads four times. The odds of this are:

     1/2 * 1/2 * 1/2 * 1/2 = 1/16

    That is, there’s a 1/16 chance that N in this case is prime.

Назад: 8:
Дальше: 10: