Advertisement
triclops200

FracSimp

Nov 5th, 2012
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. typedef struct tuple
  4. {
  5.     int x;
  6.     int y;
  7. } tuple;
  8. tuple tupCons(int x, int y)
  9. {
  10.     tuple res;
  11.     res.x = x;
  12.     res.y = y;
  13.     return res;
  14.  
  15. }
  16. inline int min(int a, int b) { return a<=b ? a : b;}
  17. tuple fracSimp(int num, int denom)
  18. {
  19.     int m = min(num,denom);
  20.     int i;
  21.     for(i = m; i > 1; i --)
  22.         if(num %i == 0 && denom %i == 0)
  23.             return fracSimp(num/i,denom/i);
  24.     return tupCons(num,denom);
  25. }
  26. int main(int argc, char**argv){
  27.     unsigned char gfrac = 0;
  28.     char * istring = argv[0];
  29.     int i;
  30.     for(i = 1; i < argc; i++)
  31.     {
  32.         if(!strcmp(argv[i],"--help") || !strcmp(argv[i],"-h"))
  33.         {
  34.             printf(
  35.                     "Usage: %s [Options] [Fraction]\n"
  36.                     "--help\t\t\t\t-h\t\tDisplay this help message\n"
  37.                     "--expression\t[fraction]\t-e [fraction]\tUse this fraction\n"
  38.                     ,argv[0]);
  39.             return 0;
  40.         }
  41.         if(!strcmp(argv[i],"--expression") || !strcmp(argv[i],"-e"))
  42.         {
  43.             gfrac = 1;
  44.             if(i+1 >= argc)
  45.             {
  46.                 printf("%s requires the next argument to be a fraction\n",argv[i]);
  47.                 return 1;
  48.             }
  49.             if(argv[i+1][0] =='-')
  50.             {
  51.                 printf("%s requires the next argument to be a fraction\n",argv[i]);
  52.                 return 1;
  53.             }
  54.             istring=argv[i+1];
  55.         }
  56.         if(argv[i][0]!='-' && !gfrac)
  57.         {
  58.             istring = argv[i];
  59.             gfrac=1;
  60.         }
  61.     }
  62.     int a,b;
  63.     if(!gfrac){
  64.         printf("Give me a fraction (1/2, 9/7, etc): ");
  65.         scanf("%d/%d",&a,&b);
  66.     }else
  67.     {
  68.         sscanf(istring,"%d/%d",&a,&b);
  69.     }
  70.     if(!b)
  71.     {
  72.         printf("ERROR: DIVISION BY 0\n");
  73.         return 1;
  74.     }
  75.     tuple res = fracSimp(a,b);
  76.     if(!gfrac)
  77.         printf("Simplified: %d/%d\n",res.x,res.y);
  78.     else
  79.         printf("%d/%d\n",res.x,res.y);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement