/*Divq.c */
/* dividing two quaternions, given the 8 integer coefficients in the
     1, i, j, k order   P/Q = R */
#include <stdio.h>
void MULT(int*,int*,int*);
void PRNT(int*);

void main(void)
{
int I,P[5],Q[5], CONJQ[5],R[5],S[5],ABSVALQ;
char CH;

  puts("The DIVISION of two quaternions each with integer coefficients");
  puts("if a term is missing, then use zero (0) as coefficient\n");
  puts("The FIRST quaternion is to be divided by the SECOND quaternion\n");
LP:
  puts("FIRST quaternion:");
  puts("Input 4 integer coefficients, separated by spaces. Then press Enter");
  for (I=0; I<4; I++) scanf("%d",&P[I]);

  puts("SECOND quaternion:");
  puts("Input 4 integer coefficients, separated by spaces. Then press Enter");
  for (I=0; I<4; I++) scanf("%d",&Q[I]);
  getchar();  /* dummy pause */

  CONJQ[0]=Q[0]; CONJQ[1]=-Q[1]; CONJQ[2]=-Q[2]; CONJQ[3]=-Q[3];
  ABSVALQ = Q[0]*Q[0] +Q[1]*Q[1] +Q[2]*Q[2] +Q[3]*Q[3];

  MULT(P,CONJQ,R);
  printf("\nRight division: p x (inverse of q) = r = "); PRNT(R);
    printf("\n   (divide coefficients by %d)\n",ABSVALQ);

  MULT(CONJQ,P,S);
  printf("\nLeft division:  (inverse of q) x p = s = "); PRNT(S);
    printf("\n   (divide coefficients by %d)\n",ABSVALQ);
  printf("\nmore?  "); CH = (char)getchar();
  if (CH=='Y' || CH=='y') goto LP;
}

/***********************/

void MULT(int* P1,int* P2,int* P3)
 /* receive two pairs of quadruples of real numbers pointed to by P1,P2;
    return a quadruple pointed to by P3, the quaternion product of the two
    the first two quadruples */
{
 int a1,b1,c1,d1,a2,b2,c2,d2,a,b,c,d;

 a1=*P1; P1++;  b1=*P1; P1++;  c1=*P1; P1++;  d1=*P1;
 a2=*P2; P2++;  b2=*P2; P2++;  c2=*P2; P2++;  d2=*P2;

 a = a1*a2 - b1*b2 - c1*c2 - d1*d2;
 b = b1*a2 + a1*b2 - d1*c2 + c1*d2;
 c = c1*a2 + d1*b2 + a1*c2 - b1*d2;
 d = d1*a2 - c1*b2 + b1*c2 + a1*d2;


 *P3=a; P3++;  *P3=b; P3++;  *P3=c; P3++;  *P3=d;
 return;
}

/***************/

void PRNT(int* P)    /* print out coeffs of quaternions in special form */
{
 int I;  char UNIT[] = " ijk";

 if (P[0]) printf("%d ",P[0]);
 for (I=1; I<4; I++) if (P[I])
  {
   if (P[I]==1) printf("+ %c ",UNIT[I]); else
   if (P[I]==-1) printf("- %c ",UNIT[I]);   else
   if (P[I]>1)  printf("+ %d%c ",P[I],UNIT[I]);    else
   if (P[I]<1)  printf("- %d%c ",-P[I],UNIT[I]);
  }
}

