Hello Everyone, how y'all are fine.
In this blog, we are gonna try to build program for Euclid's Division Lemma.
It just a mathematical theorem that states that "Given positive integers a and b, there exist unique integers q and r such that a = bq +r, 0< r < b".
Here basically 'a' is dividend, 'b' is divisor, 'q' is quotient and 'r' is remainder.
This is user to find the HCF(Highest Common Factor) of two numbers.
We are going to build program to do exactly that.
I am using C programming language, however this can be done using any programming language.
So I created a new C program file using vim and I used the below code.
=======
Code
=======
#include <stdio.h>
void main(){
int num1,num2,a,b,q,r;
printf("Enter a number: ");
scanf("%d",&num1);
printf("Enter another number: ");
scanf("%d",&num2);
if(num1>num2){
b = num1;
r = num2;
}else{
b = num2;
r = num1;
}
do{
a = b;
b = r;
q = a/b;
r = a%b;
printf("%d = (%d*%d)+%d\n",a,b,q,r);
}while(r !=0);
printf("HCF is %d\n",b);
}
========================================
If you see carefully, initially I stored the values in b and r instead of a and b. This is because as we enter the loop, we assign the value of b to a and r to b which needs to be done from the second iteration. We can assign the values to a and b at first and have condition to assign the value of b to a and r to b from second iteration, however that would require more lines of code. Kindly note that this code may not be the best approach to solve this problem, however it is the approach that I took to solve this.
Once done, it's time to compile and test the code.
So, we have compiled and tested the code and it looks to be running fine.
That's all for this blog, thanks for reading and have a wonderful day ahead.
Comments
Post a Comment