The Wayback Machine - https://web.archive.org/web/20241009162942/https://www.geeksforgeeks.org/birthday-paradox/
Open In App

Birthday Paradox

Last Updated : 19 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

How many people must be there in a room to make the probability 100% that at-least two people in the room have same birthday? 
Answer: 367 (since there are 366 possible birthdays, including February 29). 
The above question was simple. Try the below question yourself.

How many people must be there in a room to make the probability 50% that at-least two people in the room have same birthday? 
Answer: 23 
The number is surprisingly very low. In fact, we need only 70 people to make the probability 99.9 %.
Let us discuss the generalized formula.

What is the probability that two persons among n have same birthday? 
Let the probability that two people in a room with n have same birthday be P(same). P(Same) can be easily evaluated in terms of P(different) where P(different) is the probability that all of them have different birthday.
P(same) = 1 – P(different)
P(different) can be written as 1 x (364/365) x (363/365) x (362/365) x …. x (1 – (n-1)/365)
How did we get the above expression? 
Persons from first to last can get birthdays in following order for all birthdays to be distinct: 
The first person can have any birthday among 365 
The second person should have a birthday which is not same as first person 
The third person should have a birthday which is not same as first two persons. 
……………. 
…………… 
The n’th person should have a birthday which is not same as any of the earlier considered (n-1) persons.

Approximation of above expression 
The above expression can be approximated using Taylor’s Series. 
e^{x}=1+x+\frac{x^{2}}{2!}+...
provides a first-order approximation for ex for x << 1:
e^{x}\approx 1+x
To apply this approximation to the first expression derived for p(different), set x = -a / 365. Thus,
\Large{e^{\frac{-a}{365}}\approx 1-\frac {a}{365}}
The above expression derived for p(different) can be written as 
1 x (1 – 1/365) x (1 – 2/365) x (1 – 3/365) x …. x (1 – (n-1)/365)
By putting the value of 1 – a/365 as e-a/365, we get following.
\approx 1\times e^{\frac{-1}{365}}\times e^{\frac{-2}{365}}...\times e^{\frac{-(n-1)}{365}}
\approx 1\times e^{\frac{-(1+2+...+(n-1))}{365}}
\approx 1\times e^{\frac {-(n(n-1))/2}{365}}
Therefore,
p(same) = 1- p(different) 
\approx 1-e^{-n(n-1)/(2 \times 365)}
An even coarser approximation is given by
p(same) 
\approx 1-e^{-n^{2}/(2 \times 365)}
By taking Log on both sides, we get the reverse formula.
n \approx \sqrt{2 \times 365 ln\left ( \frac{1}{1-p(same)} \right )}
Using the above approximate formula, we can approximate number of people for a given probability. For example the following C++ function find() returns the smallest n for which the probability is greater than the given p.

Implementation of approximate formula. 

The following is program to approximate number of people for a given probability.  

C++

// C++ program to approximate number of people in Birthday Paradox
// problem
#include <cmath>
#include <iostream>
using namespace std;
 
// Returns approximate number of people for a given probability
int find(double p)
{
    return ceil(sqrt(2*365*log(1/(1-p))));
}
 
int main()
{
   cout << find(0.70);
}

                    

Java

// Java program to approximate number
// of people in Birthday Paradox problem
class GFG {
     
    // Returns approximate number of people
    // for a given probability
    static double find(double p) {
         
        return Math.ceil(Math.sqrt(2 *
            365 * Math.log(1 / (1 - p))));
    }
     
    // Driver code
    public static void main(String[] args)
    {
         
        System.out.println(find(0.70));
    }
}
 
// This code is contributed by Anant Agarwal.

                    

Python3

# Python3 code to approximate number
# of people in Birthday Paradox problem
import math
 
# Returns approximate number of
# people for a given probability
def find( p ):
    return math.ceil(math.sqrt(2 * 365 *
                     math.log(1/(1-p))));
 
# Driver Code
print(find(0.70))
 
# This code is contributed by "Sharad_Bhardwaj".

                    

C#

// C# program to approximate number
// of people in Birthday Paradox problem.
using System;
 
class GFG {
      
    // Returns approximate number of people
    // for a given probability
    static double find(double p) {
          
        return Math.Ceiling(Math.Sqrt(2 *
            365 * Math.Log(1 / (1 - p))));
    }
      
    // Driver code
    public static void Main()
    {        
    Console.Write(find(0.70));
    }
}
  
// This code is contributed by nitin mittal.

                    

PHP

<?php
// PHP program to approximate
// number of people in Birthday
// Paradox problem
 
// Returns approximate number
// of people for a given probability
function find( $p)
{
    return ceil(sqrt(2 * 365 *
                     log(1 / (1 - $p))));
}
 
// Driver Code
echo find(0.70);
 
// This code is contributed by aj_36
?>

                    

Javascript

<script>
 
// JavaScript program to approximate number
// of people in Birthday Paradox problem
 
// Returns approximate number of
// people for a given probability
function find( p){
    return Math.ceil(Math.sqrt(2*365*Math.log(1/(1-p))));
}
document.write(find(0.70));
 
</script>

                    

Output
30

Time Complexity: O(log n)
Auxiliary Space: O(1)

Source: 
http://en.wikipedia.org/wiki/Birthday_problem

Applications: 
1) Birthday Paradox is generally discussed with hashing to show importance of collision handling even for a small set of keys. 
2) Birthday Attack
Below is an implementation:

C

#include<stdio.h>
int main(){
 
    // Assuming non-leap year
    float num = 365;
 
    float denom = 365;
    float pr;
    int n = 0;
    printf("Probability to find : ");
    scanf("%f", ≺);
 
    float p = 1;
    while (p > pr){
        p *= (num/denom);
        num--;
        n++;
    }
 
    printf("\nTotal no. of people out of which there "
          " is %0.1f probability that two of them "
          "have same birthdays is %d ", p, n);
 
    return 0;
}

                    

C++

// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
 
int main(){
  
    // Assuming non-leap year
    float num = 365;
  
    float denom = 365;
    float pr;
    int n = 0;
    cout << "Probability to find : " << endl;
    cin >> pr;
  
    float p = 1;
    while (p > pr){
        p *= (num/denom);
        num--;
        n++;
    }
  
    cout <<  " Total no. of people out of which there is " << p
    << "probability that two of them have same birthdays is  "  << n << endl;
  
    return 0;
}
 
// This code is contributed by sanjoy_62.

                    

Java

class GFG{
  public static void main(String[] args){
 
    // Assuming non-leap year
    float num = 365;
 
    float denom = 365;
    double pr=0.7;
    int n = 0;
 
 
    float p = 1;
    while (p > pr){
      p *= (num/denom);
      num--;
      n++;
    }
 
    System.out.printf("\nTotal no. of people out of which there is ");
    System.out.printf( "%.1f probability that two of them "
                      + "have same birthdays is %d ", p, n);
  }
}
 
// This code is contributed by Rajput-Ji

                    

Python3

if __name__ == '__main__':
 
    # Assuming non-leap year
    num = 365;
 
    denom = 365;
    pr = 0.7;
    n = 0;
 
    p = 1;
    while (p > pr):
        p *= (num / denom);
        num -= 1;
        n += 1;
     
 
    print("Total no. of people out of which there is ", end="");
    print ("{0:.1f}".format(p), end="")
    print(" probability that two of them " + "have same birthdays is ", n);
 
# This code is contributed by Rajput-Ji

                    

C#

using System;
public class GFG {
  public static void Main(String[] args) {
 
    // Assuming non-leap year
    float num = 365;
 
    float denom = 365;
    double pr = 0.7;
    int n = 0;
 
    float p = 1;
    while (p > pr) {
      p *= (num / denom);
      num--;
      n++;
    }
 
    Console.Write("\nTotal no. of people out of which there is ");
    Console.Write("{0:F1} probability that two of them have same birthdays is {1} ", p, n);
  }
}
 
// This code is contributed by Rajput-Ji

                    

Javascript

<script>
 
        // Assuming non-leap year
        var num = 365;
 
        var denom = 365;
        var pr = 0.7;
        var n = 0;
 
        var p = 1;
        while (p > pr) {
            p *= (num / denom);
            num--;
            n++;
        }
 
        document.write("\nTotal no. of people out of which there is ");
        document.write(p.toFixed(1)+" probability that two of them " + "have same birthdays is "+ n);
 
// This code is contributed by Rajput-Ji
</script>

                    

Output
Probability to find : 
Total no. of people out of which there  is 0.0 probability that two of them have same birthdays is 239 

Time Complexity: O(log n)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Program to print Happy Birthday
After a lot of programming algorithms, it's my turn to wish for a programmer friend. Send this code to your coder friend and give him/her a surprise on his/her birthday! C/C++ Code // CPP program to print Happy Birthday #include<bits/stdc++.h> using namespace std; int main() { // Print first row char ch = '@'; for(int i=1; i<=34; i++) { if
8 min read
Birthday Gift: Counting integer Arrays with interesting properties
Your birthday is coming soon and one of your friends, Alex, is thinking about a gift for you. He knows that you really like integer arrays with interesting properties. He selected two numbers, N and K, and decided to write down on paper all integer arrays of length K (in form a[1], a[2], …, a[K]), where every number a[i] is in range from 1 to N, an
6 min read
Array Data Structure Guide
An array data structure is a fundamental concept in computer science that stores a collection of elements in a contiguous block of memory. It allows for efficient access to elements using indices and is widely used in programming for organizing and manipulating data. Learn Basics of Array: Introduction to Arrays – Data Structure and Algorithm Tutor
3 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. What is a Linked List? A linked list is a linear data structure that consists of a series of nodes connected
4 min read
Binary Search Tree
A Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the parent node. This hie
3 min read
Dynamic Programming or DP
Dynamic Programming is a method used in mathematics and computer science to solve complex problems by breaking them down into simpler subproblems. By solving each subproblem only once and storing the results, it avoids redundant computations, leading to more efficient solutions for a wide range of problems. This article provides a detailed explorat
7 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. For Example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character wit
6 min read
Stack Data Structure
A Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last. Table of Content What is Stack D
4 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
DSA has been one of the most popular go-to topics for any interview, be it college placements, software developer roles, or any other technical roles for freshers and experienced to land a decent job. If you are among them, you already know that it is not easy to find the best DSA interview questions among the vast pool of available problems. So he
4 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of the node. The AVL tree is named after its inventors, Georgy
3 min read
Top 50 Array Coding Problems for Interviews
Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step. Level 1Problems Practice Find the Minimum and Maximum Element in an Array Solve Array Reverse Solve Write a Program to Cyclic
3 min read
Program for Decimal to Binary Conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number. Examples of Decimal to Binary:  Input : 7Output : 111Input : 10Output : 1010Input: 33Output: 100001Recommended PracticeDecimal to binaryTry It!Brute force ApproachFor Example: If the decimal number is 10. Step 1: Remaind
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the first pass, the maximum element goes to end (its cor
8 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element and swap it with the first element. This way we get
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use Binary Heap so that we can quickly find and move t
15 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and p
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Prim’s Algorithm for Minimum Spanning Tree (MST)
Introduction to Prim's algorithm:We have discussed Kruskal's algorithm for Minimum Spanning Tree. Like Kruskal's algorithm, Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way. The algorithm starts with an
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
0/1 Knapsack Problem
Prerequisites: Introduction to Knapsack Problem, its Types and How to solve them Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum
15+ min read
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Like Trees, we traverse all adjacent one by one, when we traverse an adjacent, we finish traversal of all vertices reachable through the adjacent completely. After we finish one adjacent and its reachable, we go to the next adjacent and finish all reachable th
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read
Maximum Subarray Sum - Kadane's Algorithm
Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -4}Output: -2Explanation: The subarray {-2} has the largest sum -2. Input: arr[] = {5, 4, 1, 7, 8}Output: 25
10 min read
Practice Tags :