微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

大数取余数-----x的y次方取余数

大数取余数---

题目描述:


输入一个位数不超过10^6的整数a,求a%5并输出


//此题肯定不能用long,int表示要输入的这个整数,这两种类型表示的范围没有题目要求的那么大;可用string

#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
cin>>str;
int i;
int rem=0;
for(i=0;i<str.length();i++){
rem=rem*10+str[i]-'0';
rem=rem%5;//这里对其他数取余的话,5可以换成其他的数
}
cout<<rem<<endl;
}

x的y次方取余数

Google Round B

https://code.google.com/codejam/contest/5254487/dashboard#s=p1

只会做small practice。。。

涉及到x的y次方,对mod取余数,如下。

/***
	 * 
	 * @param x
	 * @param y
	 * @param mod
	 * @return
	 */
	public static long power(long x,long y,long mod) {
		long t = 1;
		while (y > 0) {
			if (y % 2 == 1) {
				y -= 1;
				t = t*x%mod;
			} else {
				y /= 2;
				x = x*x%mod;
			}
		}
		return t%mod;
	}

对于small practice的解法

import java.io.bufferedoutputstream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;


public class RoundBProblemB {

	public static void main(String[] args) throws FileNotFoundException {
		PrintStream out = new PrintStream(new bufferedoutputstream(new FileOutputStream("outB-small.txt")));
		System.setout(out);
		System.setErr(out);
		
		Scanner scanner = new Scanner(new FileInputStream("B-small-practice.in"));
		int T = scanner.nextInt();
		for (int i = 1; i <= T; i++) {
			int A = scanner.nextInt();
			int B = scanner.nextInt();
			int N = scanner.nextInt();
			int K = scanner.nextInt();
			System.out.println("Case #" + i +": " + Solve(A,B,N,K));
		}
		
		out.flush();
		out.close();
	}
	public static int Solve(long A,long B,long N,long K) {
		int ans = 0;
		int i = 1,j = 1;
		for (i = 1; i <= N; i++) {
			long sumA = power(i,A,K);
			sumA = sumA%K;
			for (j = 1; j <= N; j++) {
				if (i == j) {
					continue;
				} else {
					long sumB = power(j,K);
					sumB = sumB%K;
					if ((sumA + sumB)%K == 0) {
						ans++;
					}
				}
			}
		}
		return ans;
	}
	/***
	 * 
	 * @param x
	 * @param y
	 * @param mod
	 * @return
	 */
	public static long power(long x,long mod) {
		long t = 1;
		while (y > 0) {
			if (y % 2 == 1) {
				y -= 1;
				t = t*x%mod;
			} else {
				y /= 2;
				x = x*x%mod;
			}
		}
		return t%mod;
	}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐