P-sequences


Problem Statement :


We call a sequence of N natural numbers (a1, a2, ..., aN) a P-sequence, if the product of any two adjacent numbers in it is not greater than P. In other words, if a sequence (a1, a2, ..., aN) is a P-sequence, then ai * ai+1 ≤ P ∀ 1 ≤ i < N

You are given N and P. Your task is to find the number of such P-sequences of N integers modulo 109+7.

Input Format

The first line of input consists of N
The second line of the input consists of P.

Constraints

2 ≤ N ≤ 103
1 ≤ P ≤ 109
1 ≤ ai

Output Format

Output the number of P-sequences of N integers modulo 109+7.



Solution :



title-img


                            Solution in C :

In C++ :





#include<math.h>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<stdio.h>
#include<map>
#include<ext/hash_map>
#include<ext/hash_set>
#include<set>
#include<string>
#include<assert.h>
#include<vector>
#include<time.h>
#include<queue>
#include<deque>
#include<sstream>
#include<stack>
#include<sstream>
#define MA(a,b) ((a)>(b)?(a):(b))
#define MI(a,b) ((a)<(b)?(a):(b))
#define AB(a) (-(a)<(a)?(a):-(a))
#define X first
#define Y second
#define mp make_pair
#define pb push_back
#define pob pop_back
#define ep 0.0000000001
#define Pi 3.1415926535897932384626433832795
using namespace std;
using namespace __gnu_cxx;
const long long  MO=1000000000+7;
int x,y,i,j,k,n,m,mid,l,r;
int a[100000],p,kk;
long long b[2][100000];
int main()
{
    cin>>n>>p;
    kk=k=int(sqrt(p));
    for (i=1;i<=k;i++) a[i]=i;
    for (i=kk;i>=1;i--)
    {
        if (p/i>a[k]) {k++; a[k]=p/i;}
    }
    for (i=1;i<=k;i++)
    b[1][i]=a[i];
    b[0][0]=0;
    b[1][0]=0;
    for (i=2;i<=n;i++)
    {
        r=k;
        for (j=1;j<=k;j++){
            while (a[r]*a[j]>p) r--;
            b[(i&1)][j]=(b[(!(i&1))][r]*(a[j]-a[j-1])+b[(i&1)][j-1])%MO;
   //     cout<<b[(i&1)][j]<<" "<<a[j]<<" -- ";
        }
   //     cout<<endl;
    }
    cout<<b[(n&1)][k]<<endl;

    return 0;
}








In Java :





import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Nipuna Samarasekara
 */
public class Solution {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		FastPrinter out = new FastPrinter(outputStream);
		Task3 solver = new Task3();
		solver.solve(1, in, out);
		out.close();
	}
}

class Task3 {
    /////////////////////////////////////////////////////////////
  static long mod=1000000007;
    public void solve(int testNumber, FastScanner in, FastPrinter out) {
   long N=in.nextInt(),p=in.nextInt();
   int sqrt= (int)Math.sqrt(p) ;
     long[][] finishes= new long[2][1+sqrt];
     long[][] finpdivupw= new long[2][1+sqrt];
        for (int i = 1; i <=sqrt ; i++) {
          finishes[0][i]=1;
          if(i<sqrt)
          finpdivupw[0][i]= p/i - p/(i+1);
        }
        finpdivupw[0][sqrt]=p/sqrt-sqrt;
       int cur=0,prev=1;
        for (int i = 0; i < N-1; i++) {
          cur^=1;
          prev^=1;
            long sum=0;
            for (int j = 1; j < sqrt ; j++) {
                sum+=finishes[prev][j];
                if(sum>=mod)sum%=mod;
                long val=sum*(p/j - p/(j+1));
                val%=mod;
                finpdivupw[cur][j]=val;

            }
            sum+=finishes[prev][sqrt];
            long val=  sum*(p/sqrt-sqrt);
            finpdivupw[cur][sqrt]= val%mod;
            for (int j = sqrt; j >= 1; j--) {
              sum+=finpdivupw[prev][j];
                if(sum>=mod)sum%=mod;
                finishes[cur][j]=sum;
            }



        }
        long ans=0;
        for (int i = 1; i <= sqrt ; i++) {
           ans+=finishes[cur][i];
            if(ans>=mod)ans%=mod;
           ans+=finpdivupw[cur][i];
            if(ans>=mod)ans%=mod;
        }
        out.println(ans);
    }
}

class FastScanner extends BufferedReader {

    public FastScanner(InputStream is) {
        super(new InputStreamReader(is));
    }

    public int read() {
        try {
            int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
            return ret;
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

    static boolean isWhiteSpace(int c) {
        return c >= 0 && c <= 32;
    }

    public int nextInt() {
        int c = read();
        while (isWhiteSpace(c)) {
            c = read();
        }
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int ret = 0;
        while (c >= 0 && !isWhiteSpace(c)) {
            if (c < '0' || c > '9') {
                throw new NumberFormatException("digit expected " + (char) c
                        + " found");
            }
            ret = ret * 10 + c - '0';
            c = read();
        }
        return ret * sgn;
    }

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }

}

class FastPrinter extends PrintWriter {

    public FastPrinter(OutputStream out) {
        super(out);
    }

    public FastPrinter(Writer out) {
        super(out);
    }


}








In C :





#include <stdio.h>

#define P 1000000007LL

long long b[100000][3],i,j,k,l,m,n,t;
long long a[1010][65000];

int main()
{

scanf("%lld %lld",&n,&t);

k = 1;
l = 0;

while(k<=t)
 {
   b[l][0] = k;
   b[l][1] = t/(t/k);
   b[l][2] = b[l][1] - b[l][0] + 1;
   k = b[l][1] + 1;
   l++;
 }

for(i=0;i<l;i++) a[0][i] = 0;
a[0][0] = 1;

for(i=1;i<=n;i++)
{
 k = 0;
 for(j=0;j<l;j++)
   {
    k = (k+a[i-1][j]*b[j][2])%P;
    a[i][l-1-j] = k;   
   }
}

k = 0;

for(i=0;i<l;i++) k = (k+a[n][i]*b[i][2])%P;

printf("%lld\n",k);

return 0;
}








In Python3 :





#!/bin/python3

import os
import sys

#
# Complete the pSequences function below.
#
def pSequences(n, p):

    MOD = 10**9+7

    Pf = set()
    for i in range(1,int(p**0.5)+1) :
        Pf.add(i)
        Pf.add(p//i)
    Pf = sorted(Pf)
    # print(Pf)

    Ps = []
    for f in Pf :
        Ps.append(f)

    Pfd = [0]
    for i in range(1, len(Pf)) :
        Pfd.append(Pf[i]-Pf[i-1])

    # print(Pfd)
    for n in range(1,n):
    #    print(Ps)
        Ps_ = []
        Ps_.append(Ps[-1])
        for i in range(1,len(Pf)) :
            Ps_.append((Ps_[-1] + Pfd[i] * Ps[-(i+1)]) % MOD)
        Ps = Ps_
            
    # print(Ps)
    return(Ps[-1])

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    p = int(input())

    result = pSequences(n, p)

    fptr.write(str(result) + '\n')

    fptr.close()
                        








View More Similar Problems

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →