CodeChef Sereja and GCD

Sereja and GCD

 
Problem code: SEAGCD
 

All submissions for this problem are available.

Read problems statements in Mandarin Chinese and Russian.

In this problem Sereja is interested in the number of arrays of integers, A1, A2, ..., AN, with 1 ≤ Ai ≤ M, such that the greatest common divisor of all of its elements is equal to a given integer D.

Find the sum of answers to this problem with D = L, D = L+1, ..., D = R, modulo 109+7.

Input

The first line of the input contains an integer T - the number of test cases. T tests follow, each containing a single line with the values of N, M, L, R.

Output

For each test case output the required sum, modulo 109+7.

Constraints

  • 1T10
  • 1LRM

Subtasks

  • Subtask #1: 1N, M10 (10 points)
  • Subtask #2: 1N, M1000 (30 points)
  • Subtask #3: 1N, M107 (60 points)

Example

Input:
2
5 5 1 5
5 5 4 5

Output:
3125
2

对于一个 d , 1~m中有 m/d个数是 d的倍数, 自然就是有 (m/d)^n种排列方法。

然而 , 这些排列当中,元素必须包含 d , 只要它减去那些只包含它的倍数的序列即可得出结果。

#include <iostream>
#include <cstdio>
using namespace std ;
typedef long long LL;
const int mod = 1e9+7;
const int N = 10000100;
LL A[N] ;
LL q_pow( LL a , LL b ) {
    LL res = 1 ;
    while( b ) {
        if( b&1 ) res =  res * a  % mod ;
        a = a * a % mod ;
        b >>= 1;
    }
    return res ;
}
int main() {
//    freopen("in.txt","r",stdin);
    int _ ; cin >> _ ;
    while( _-- ) {
        LL n , m , l , r ;
        cin >> n >> m >> l >> r ;
        for( int d = m ; d >= l ; --d ) {
            if( d == m || m/d != m/(d+1) ) A[d] = q_pow( m/d , n );
            else A[d] = A[d+1] ;
        }
        for( int i = m ; i >= l ; --i ) {
            for( int j = i + i ; j <= m ; j += i ) {
                A[i] =( ( A[i] - A[j] ) % mod + mod ) % mod ;
            }
        }
        LL ans = 0 ;
        for( int i = l ; i <= r ; ++i )
            ans = ( ans + A[i] ) % mod ;
        cout << ans << endl ;
    }
}
View Code

 

posted @ 2015-02-21 00:45  hl_mark  阅读(322)  评论(0编辑  收藏  举报