Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 19th, 2012  |  syntax: None  |  size: 2.14 KB  |  hits: 4  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void dec2bin(int dec, char *bin);
  5. int SaM(int x, int p, char *b_bin);
  6.  
  7. int main(int argc, char *argv[]) {
  8.         int a, b, m, result;
  9.         char b_bin[32];
  10.  
  11.         if (argc != 4) {
  12.                 fprintf(stderr, "Usage: %s [a] [b] [m]\n for a^b mod m", argv[0]);
  13.                 return -1;
  14.         }
  15.          
  16.         a = atoi(argv[1]);
  17.         b = atoi(argv[2]);
  18.         m = atoi(argv[3]);
  19.  
  20.         memset(b_bin, 0, 32);
  21.          
  22.         dec2bin(b, b_bin);
  23.         printf("######################################\n*Binary value of %d is %s\n######################################\n\n", b, b_bin);
  24.         printf("######################################\n*I am now calculating %d^%d mod %d \n######################################\n", a, b, m);
  25.         result = SaM(a, m, b_bin);
  26.         printf("######################################\n*My result is %d\n######################################\n", result);
  27.         return 1;
  28. }
  29.  
  30. void dec2bin(int dec, char *bin) {
  31.          
  32.         /* This function returns the binary value of the given integer in the following pattern:
  33.          * least significant bit --------------------> most significant bit  
  34.          */
  35.  
  36.         int i = 0;
  37.         while ( dec > 0 ) {
  38.                 if(dec % 2 == 0)
  39.                         bin[i] = '0';
  40.                 if(dec % 2 == 1)
  41.                         bin[i] = '1';
  42.                 dec = dec / 2;
  43.                 i++;
  44.         }
  45. }
  46.  
  47. int SaM(int x, int m, char *y_bin) {
  48.  
  49.         /* This implements the actual square and multiply algorithm for x^y, the problem is that the bin algorithm above returns the bit sequence in the wrong order, so we need to run backwards here
  50.          */
  51.         int MsB=0;
  52.         while (y_bin[++MsB] != '\0');
  53.         int i, a;  
  54.         a = x;
  55.         for (i = MsB-2; i >= 0; i--) {
  56.                 x = (x*x) % m;
  57.                 if (y_bin[i] == '1')  
  58.                         x = (a*x) % m;
  59.          
  60.                 printf("got an %c my result is %d \n", y_bin[i], x);
  61.         }
  62.          
  63.         return x;
  64.  
  65. }