N Students

Brain Teasers with Coding Study

Few companies ask the below brain teaser to the candidates during the interview.

There are 40 students in the class. What is the possibility that at least 2 students share the same day of birth?

But what if it is a coding challenge:

There are N students in the class. What is the possibility that at least 2 students share the same day of birth? (Provided condition: No student is born in a leap year.)

Write a code that calculates the required probability.

The puzzles from my book “Brain Teasers with Coding For Data Scientist” are published on this link. Also, don’t forget to check my coding puzzle books “Brain Teasers with Coding For Data Scientist 2: 9 New Computational Puzzles” and “Puzzles with Coding: Puzzles for Everyone” and “Computational Puzzles To Flex Your Brain: 50 original puzzles to sharpen computing mind and mathematical skills at Amazon. For purchasing my books or related queries, feel free to contact me. In these books, you will find interesting brain teasers those are suitable for coders as well as non-coders. Coding solutions are also provided with Python code. So, grab a copy of those books and jump into the world of fascinating and exciting brain teasers.

Solution:

General Formula:

Required probability = 1 – ( 365! / ((365-N)! * 365N ))

Where N = Number of students in a class

Coding Solution:

# N Number of Students in Class
N = int (input('Enter Number of Students(N):')) 
mul1 = 1
for x in range(365-N+1,366):
    mul1 = mul1 * x

base = 365
exponent = N
mul2 = pow(base, exponent)
print('Probability of any two share same birthday:',1-(mul1/mul2))

Note : (Keeping non-coder readers in mind, code optimization is not fully utilized.)

Test Output 1:
Enter Number of Students(N):40
Probability of any two share same birthday: 89.1231809817949 %

Test Output 2:
Enter Number of Students(N):100
Probability of any two share same birthday: 99.99996927510722 %