Solution of 1230 - MODEX

Problem Description
source:https://uva.onlinejudge.org/external/12/1230.html

Many well-known cryptographic operations require modular exponentiation. That is, given integers x, y and n, compute xy mod n. In this question, you are tasked to program an efficient way to execute this calculation.

Input 

The input consists of a line containing the number c of datasets, followed by c datasets, followed by a line containing the number ‘0’. Each dataset consists of a single line containing three positive integers, x, y, and n, separated by blanks. You can assume that 1 < x, n < 215 = 32768, and 0 < y < 231 = 2147483648

Output 

The output consists of one line for each dataset. The i-th line contains a single positive integer z such that 
                                        z = xy 
mod n for the numbers x, y, z given in the i-th input dataset. 

Sample Input 


2 3 5 
2 2147483647 13 


Sample Output 


11

Solution:
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

int main()
{
    long int t,x,y,n,r,i,j;
    while(scanf("%ld",&t)==1 && t!=0)
    {
        for(j=1;j<=t;j++)
        {
            scanf("%ld%ld%ld",&x,&y,&n);
            r=1;
            while (y != 0)
            {
                r = (r * x * (y & 1) + r * ((y & 1) == 0)) % n;
                x = (x * x) % n;
                y >>= 1;
            }
            printf("%ld\n",r);
        }
    }
    return 0;
}
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience