欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

0x01--位运算

程序员文章站 2024-03-19 11:43:10
...

例题1:AcWing 89—a^b
0x01--位运算

快速幂取模运算标准模板,要熟练

import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long a = sc.nextLong();
		long b = sc.nextLong();
		long p = sc.nextLong();
		sc.close();
		
		long res = power(a, b, p);
		System.out.println(res); 
	}

	private static long power(long a, long b, long p) {
		long res = 1 % p;
		while(b > 0) {
			if((b & 1) == 1) res = (res * a) % p;//b的最后一位是1
			a = (a * a) % p;
			b >>= 1;
		}
		return res;
	}
}

例题2:AcWing 90–64位整数乘法
0x01--位运算

import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long a = sc.nextLong();
		long b = sc.nextLong();
		long p = sc.nextLong();
		sc.close();
		
		long res = power(a, b, p);
		System.out.println(res); 
	}

	private static long power(long a, long b, long p) {
		long res = 0;
		while(b > 0) {
			if((b & 1) == 1) res = (res + a) % p;//b的最后一位是1
			a = (a * 2) % p;
			b >>= 1;
		}
		return res;
	}
}

上一篇: MD5简介

下一篇: 谁的青春都迷茫