Greatest common divisor


/* Euclid's algorithm */

#include <stdio.h>

int main() {

   int n,m,temp;

   printf("Enter two positive integers > ");
   scanf("%d %d",&n,&m);

while ((n % m) > 0) {  /* do Euclid's algorithm */
    temp = n % m;
    n = m;
    m = temp;
}


if (m == 1)
    printf("The numbers are relatively prime.\n");
else
    printf("The largest common divisor is %d\n",m);

}

Recursive GCD


/* recursive formulation of greatest common divisor */

#include <stdio.h>

int gcd(int a, int b) {

   int q, res;

   q = a % b;
   if (q == 0)
      res = b;
   else
      res = gcd(b,q);
  return(res);
  }

int main() {

   int n,m;

   printf("Enter two positive integers > ");
   scanf("%d %d",&n,&m);

if (gcd(n,m) == 1)
    printf("The numbers are relatively prime.\n");
else
    printf("The largest common divisor is %d\n",gcd(n,m));

}


Checking primality


/* silly prime.c */
#include <stdio.h>

int main() {

     int n, p;

     printf("Input an integer bigger than 1> ");
     scanf("%d",&n);

      p = 2;
    
     while(p < n) {
          if (n % p == 0) {
             break;
             }
          else
             p = p+1; 
    }
    if (p == n)
         printf("%d is prime!\n",n);
    else
         printf("%d is not prime!\n",n);
 
}


/* better prime.c */

#include <stdio.h>

int main() {

     int n, p;
     int flag;

     printf("Input an integer bigger than 1> ");
     scanf("%d",&n);

      flag = 0;
      p = 2;
     
     while(p*p <= n) {
          if (n % p == 0) {
             flag = 1;
             break;
             }
          else
             p = p+1; 
    }
    if (flag == 0)
         printf("%d is prime!\n",n);
    else
         printf("%d is not prime!\n",n);
}