May 11, 2023 Brute Force Techniques I
This is a description Greatest Common Divisor
#include <stdio.h>
int gcd(int m, int n)
{
if (n == 0) return m;
return gcd(n, m % n);
}
void main()
{
int m, n;
printf("Enter the numbers: ");
scanf("%d %d", &m, &n);
printf("The GCD of %d and %d is %d.", m, n, gcd(m, n));
}
Square Root
#include <stdio.h>
#include <stdlib.h>
int sqrt(int n)
{
if (n == 0 || n == 1)
return n;
int i = 1, result = 1;
while (result < n)
{
i++;
result = i * i;
}
if (result == n)
return i;
else
{
printf("ERROR | No square root found!");
exit(0);
}
}
void main()
{
int n;
printf("Enter the number: ");
scanf("%d", &n);
printf("The square root of %d is %d.", n, sqrt(n));
}
Towers of Hanoi
#include <stdio.h>
void towers(int n, char src, char aux, char dest)
{
if (n == 1)
{
printf("\nmove disk 1 from %c to %c", src, dest);
return;
}
towers(n-1, src, dest, aux);
printf("\nmove disk %d from %c to %c", n, src, dest);
towers(n-1, aux, src, dest);
}
void main()
{
int n;
printf("Enter number of disks: ");
scanf("%d", &n);
towers(n, 'A', 'B', 'C');
}