Garlic 2018 Waterloo Cup B Group simulation game (v) D. Code Blank: Fast Power

Source: Internet
Author: User

"topic link": https://nanti.jisuanke.com/t/25087

"Topic description":

The integer power of a number is often used in our calculations, but how can we work out the result in the time of O (log (n)).

The code in the Code box is an implementation, please analyze and fill in the missing code to find the result of X^y mod p.

Import java.util.*;
public class Main {
public static int pw (int x, int y, int p) {
if (y = = 0) {
return 1;
}
int res =//* Fill in the necessary code here */;
if ((Y & 1)!= 0) {
res = res * x% P;
}
return res;
}
public static void Main (string[] args) {
Scanner cin = new Scanner (system.in);
int x = Cin.nextint ();
int y = Cin.nextint ();
int p = cin.nextint ();
System.out.println (PW (x, Y, p));
}
}

"Answer": PW (x, Y/2, p) * PW (x, Y/2, p)% p

"Resolution":

"Code":

Import java.util.*;
public class Main {public
    static int pw (int x, int y, int p) {
        if (y = = 0) {return
            1;
        }
        int res = PW (x, Y/2, p) * PW (x, Y/2, p)% p/* fill in the necessary code here * * *;
        if ((Y & 1)!= 0) {
            res = res * x% P;
        }
        return res;
    }
    public static void Main (string[] args) {
        Scanner cin = new Scanner (system.in);
        int x = Cin.nextint ();
        int y = Cin.nextint ();
        int p = cin.nextint ();
        System.out.println (PW (x, Y, p));
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.