HackerRank Hiring Contest - C The Simplest Sum

You are just learning to code and are finished with loops and functions. Now, you are given the following pseudocode:

/*
 * The function has two integer parameters: k and n
 * The function returns the value of sum
 */
function f(k, n) {
    sum = 0;

    for (i = 1; i  n; i += 1) {
        sum += i;
        i *= k;
    }

    return sum;
}

For three given integers , and , find the value of , where  is defined as:

Input Format

The first line of the input is an integer , the total number of queries. Each of the next  lines contains three space separated integers , and .

Constraints

Output Format

For each query, print the value of  on a new line.

Sample Input

4
2 1 5
3 1 5
4 1 5
5 1 5

Sample Output

14
13
10
5

Explanation

  • Query 2 1 5

     
     
     
     

    So, 

  • Query 3 1 5

     
     
     
     

    So, 

  • Query 4 1 5

     
     
     
     

    So, 

  • Query 5 1 5

     
     
     
     

    So, 



POINT:

要想着[r,1]-[l-1,1]来算而不是[r,l]。

接着就是简单的规律了。


#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
const LL maxn = 1e6+6;
const LL inf = 0x3f3f3f3f;
const LL mod = 1e9+7;
LL k;

LL f(LL x)
{
	if(x==0) return 0;
	LL a[300];
	LL cnt=0;
	double now = 1;
	for(LL i=1;now<=x;i++){
		a[++cnt]=(LL)now;
		a[cnt]%=mod;
		now=now*k+1;
	}
	LL ans = 0;
	for(LL i=1;i<=cnt;i++){
		(ans+=(x-a[i]+1)%mod*a[i])%=mod;
	}
	return ans;
}

int main()
{
	LL T;
	scanf("%lld",&T);
	while(T--)
	{
		LL a,b;
		scanf("%lld %lld %lld",&k,&a,&b);
		printf("%lld\n",(f(b)+mod-f(a-1))%mod);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值