SGU[117] Counting

Description

描述

Find amount of numbers for given sequence of integer numbers such that after raising them to the M-th power they will be divided by K.

求出给定一个包含N个整数的序列,其中某个数字的M次方能被K整除的数的个数。

 

Input

输入

Input consists of two lines. There are three integer numbers N, M, K (0<N, M, K<10001) on the first line. There are N positive integer numbers − given sequence (each number is not more than 10001) − on the second line.

输入包含两行。第一行包含三个整数N, M, K (0 < N, M, K < 10001)。

第二行包含N个正整数——给定的序列(每个数不超过10001)。


Output

输出

Write answer for given task.

输出给定任务的答案。


Sample Input

样例输入

4 2 50

9 10 11 12


Sample Output

样例输出

1

 

Analysis

分析

快速幂,时间复杂度为O(n logn),应该是可以过的。

要注意用int的话会溢出,所以我直接用了unsigned long long。

这道题目还有一个方法是质因数分解,求出M次方以后的各个因数个数(就是把个因子个数乘以M),然后和M的个因子的个数比较即可。

 

Solution

解决方案

快速幂:

#include <iostream>

using namespace std;

typedef unsigned long long  ull;

ull Pow(ull x, ull y, ull z);

int main()
{
	ull nTmp;
	int N, M, K;
	while(cin >> N >> M >> K)
	{
		int nCnt = 0;
		for(int i = 1; i <= N; i++)
		{
			cin >> nTmp;
			if(Pow(nTmp, M, K) == 0) { nCnt++; }
		}
		cout << nCnt << endl;
	}
	return 0;
}

ull Pow(ull x, ull y, ull z)
{
	if(y == 1) { return x % z; }
	ull nTmp = Pow(x, y / 2, z);
	if(y & 1) { return (ull)nTmp * nTmp * x % z; }
	else { return (ull)nTmp * nTmp % z; }
}

 

质因数分解:

#include <iostream>
#include <memory.h>

using namespace std;

const int MAX = 10240;

int X[MAX], Y[MAX];

void Fact(int x, int *p);

int main()
{
	int nTmp;
	int N, M, K;
	while(cin >> N >> M >> K)
	{
		int nCnt = 0;
		memset(Y, 0, sizeof(Y));
		Fact(K, Y);
		for(int i = 1; i <= N; i++)
		{
			memset(X, 0, sizeof(X));
			cin >> nTmp;
			Fact(nTmp, X);
			for(int i = 0; i < MAX; i++)
			{ X[i] *= M; }
			bool bFlag = true;
			for(int j = 0; j < MAX; j++)
			{
				if(X[j] < Y[j]) { bFlag = false; break; }
			}
			if(bFlag) { nCnt++; }
		}
		cout << nCnt << endl;
	}
	return 0;
}

void Fact(int x, int *p)
{
	for(int i = 2; i <= x; i++)
	{
		if(x % i == 0)
		{
			while(x % i == 0)
			{
				(*(p + i))++;
				x /= i;
			}
		}
	}
}

  

这道题目使用快速幂需要将整除转换成mod以后余0。

posted @ 2015-02-24 14:14  Ivy_End  阅读(218)  评论(0编辑  收藏  举报