#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define DECDATATYPE long #define BINDATATYPE char typedef struct bin_data{ BINDATATYPE data; struct bin_data *next; }BIN_DATA; BIN_DATA *head; void dec_to_bin(DECDATATYPE dec_num){ BIN_DATA *p,*q; if((head=(BIN_DATA *)malloc(sizeof(BIN_DATA)))==NULL){ printf("No free mem to allloc.\n"); exit(0); } head->data = '\0'; head->next = NULL; p=head; while(dec_num){ /* insert to the back of head node */ q=(BIN_DATA *)malloc(sizeof(BIN_DATA)); q->data = (BINDATATYPE)(dec_num & 0x1); q->next = p->next; p->next = q; /* append node to the end of list q=(BIN_DATA *)malloc(sizeof(BIN_DATA)); q->data = (BINDATATYPE)(dec_num & 0x1); q->next = NULL; p->next = q; p = q; */ dec_num = dec_num >> 1; } } DECDATATYPE square_multi(DECDATATYPE base_num, DECDATATYPE exp_num, DECDATATYPE mod_num){ DECDATATYPE result=1; BIN_DATA *p; dec_to_bin(exp_num); p=head->next; while(p){ result=result*result%mod_num; if(p->data) result=result*base_num%mod_num; p=p->next; } return result; } int main (int argc, char * argv[]) { DECDATATYPE base_num, exp_num, mod_num; if(argc < 3) { printf("args error.\n"); return 1; } base_num=atoi(argv[1]); exp_num=atoi(argv[2]); mod_num=atoi(argv[3]); printf("The mode value of base[%ld],exp[%ld],mod[%ld] is: [%ld]",base_num,exp_num,mod_num,square_multi(base_num,exp_num,mod_num)); return 0; }
平方乘算法实现
最新推荐文章于 2024-09-24 22:54:48 发布