Mathematical induction is used to prove the
Proof by induction includes three steps:
This may help us understand induction:
Suppose you have millions of dominos, spaced out perfectly. How will we know that every domino will fall when we tip the first one?
We don't have to check every single domino. We only have to prove the following:
Let's understand this through an example of proving an algorithm that calculates the
#include <iostream>using namespace std;int fact(long int n){if ((n==0)||(n==1)){return 1;}else{return n*fact(n-1);}}int main(){long int n;cout << "Enter a positive number: ";cin >> n;if (n < 0)cout << "The number is negative!";else {cout << "Factorial of " << n << " = " << fact(n);}}
Enter the input below
This is the first step of the proof. Here, we try to verify that the algorithm holds for the first number from a valid range of inputs.
As the factorial function will work on all positive integers, then the base case would be when
In this step, we prove that if the algorithm is working for any arbitrary value of
Assumption: For the program, after going through
After our assumption, we'll try to prove that it also works on
The loop variant works because the
The loop stops after
Free Resources