Sum of Consecutive Integers(有些数学思想)

Given an integer N, you have to find the number of ways you can express N as sum of consecutive integers. You have to use at least two integers.

For example, N = 15 has three solutions, (1+2+3+4+5), (4+5+6), (7+8).
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.

Each case starts with a line containing an integer N (1 ≤ N ≤ 1014).
Output
For each case, print the case number and the number of ways to express N as sum of consecutive integers.
Sample Input
5
10
15
12
36
828495
Sample Output
Case 1: 1
Case 2: 3
Case 3: 1
Case 4: 2
Case 5: 47

解题思路

题意就是给一个数,问可以有几个连续的数相加得到,我们可以设这个数为N,第一项为a1,一共m项am=a1+m-1; N=(a1+a1+m-1)m/2; 2a1=2N/m+1-m 我们可以知道2a1是偶数,2*N/m+1是奇数,所以m肯定是奇数,N/m必须是整数,也就是m是N的因数,所以我们只要求N的奇数因子的个数即可,因为题上说至少有两项,所以要减去m=1的情况。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e7;
const int max1=1e6;
bool prime[maxn+10];//这要用bool 
ll p[max1],k=0;//这个不能开到1e7不然会RE 
void check()
{
	prime[0]=prime[1]=1;
	for(ll i=2;i<maxn;i++)
	{
		if(!prime[i])
		{
			p[k++]=i;
			for(ll j=i*i;j<maxn;j+=i)
			prime[j]=1;
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin>>t;
	int s=0;
	check();
	while(t--)
	{
		ll x;
		cin>>x;
		int sum=1;
		while(x%2==0)
		{
			x/=2;//因为质数中就有2是偶数,所以把2的倍数除去
		}
		for(int i=0;i<k&&p[i]*p[i]<=x;i++)
		{
			ll cnt=0;
			while(x%p[i]==0)
			{
				cnt++;
				x/=p[i];
			}
			sum*=cnt+1;
		}
		if(x>1) sum*=2;
		printf("Case %d: %lld\n",++s,sum-1);//减一就是m=1时就有一项 
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值