1. 程式人生 > 其它 >【題解】Special Numbers

【題解】Special Numbers

原題連結:

Problem - 1594B - Codeforces

題目描述

Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.

Let's call a positive numberspecialif it can be written as a sum ofdifferentnon-negative powers ofn

n.

For example, forn=4,number17is special, because it can be written as4^0+4^2=1+16=17,but9is not.

Theofanis asks you to help him find thekk-th special number if they are sorted in increasing order.

Since this number may be too large, output it modulo10^9+7.

輸入

The first line contains a single integer

tt(1t10^4)— the number of test cases.

The first and only line of each test case contains two integersnnandkk(2n10^9;1k10^9).

輸出

For each test case, print one integer— thekk-th special number in increasing order modulo10^9+7.

輸入樣例

3
3 4
2 12
105 564

輸出樣例

9
12
3595374

分析及程式碼實現

題目要求尋找 由n的非負指數的數及他們任意的和的陣列(升序排列)的第k個數字

很難發現,k的二進位制形式中的1其實就表示累加了以該位次為冪的底數的值。

  • 比如n為3,k為13,此時k的二進位制為1101。
  • 那麼第k個以n為底的冪底數的累加就為3^0 + 3^2 + 3^3 = 3

那麼我們就可以寫出n = 3時的情況

c++程式碼實現

#include<iostream>
using namespace std;

typedef long long ll;
const ll mod = 1e9 + 7;

int main(){
    int t;
    cin >> t;
    while(t--){
        ll n, k, ret = 0, deal = 1;
        scanf("%lld%lld", &n, &k);
        while(k){
            if (k & 1)//如果當前最後一位是1,則加上deal
                ret = (ret + deal) % mod;
            deal = deal * n % mod;//處理deal
            k >>= 1;//右移一位,看k的下一個二進位制位
        }
        printf("%lld\n", ret);
    }
    return 0;
}