数学知识模板之试除法

试除法判定质数

bool is_prime(int x)
{
	if(x < 2) return false;
	for(int i = 2; i <= x / i;i ++ )
		if(x % i == 0) return false;
	return true;
}

试除法分解质因数

void divide(int x)
{
	for(int i = 2;i <= x / i;i ++ )
	{
		int s = 0;
		while(x % i == 0)
		{
			s ++;
			x /= i;
		}
		cout << i << ' ' << s << endl;
	}
	if(x) cout << x << ' ' << 1 << endl;// 如果x大于1,说明存在一个大于根号x的质因子
	
/*
如果N = p1^c1 * p2 ^ c2 * p3 ^ c3 *... * pk & ck;
约数个数 = (c1 + 1)(c2 + 1)...(ck + 1)
所有约数之和 = (p1 ^ 0 + p1 ^ 1 + ... + p1 ^ c1)* ... * (pk ^ 0 + pk ^ 1 + ... + pk ^ ck)
*/
}

试除法求所有约数

vector<int> get_dividors(int x)
{
	vector<int> res;
	for(int i = 1;i <= x / i;i ++ )
	{
		if(x % i == 0 )
		{
			res.push_back(i);
			if(x / i != i) res.push_back(x / i);
		}
	}
	sort(res.begin(),res.end());
	return res;
}


posted @ 2023-03-19 20:57  知凹  阅读(76)  评论(0)    收藏  举报