1

this is so far all i have done i am trying to optimize the code for less time.but it is not working.

for _ in range(int(input())):
n, m = map(int, input().split())
count = 0
for i in range(1, n+1):
    for j in range(1, n+1):
        if i < j <= n and ((m%i)%j) == ((m%j)%i):
            count += 1
print(count)

another approach I tried:

if i < j <= n and (m-(m%j))%i == 0:

both condition give correct result.but show time limit exceed

what should i do.thanks

sam
  • 1,819
  • 1
  • 18
  • 30

3 Answers3

2

Since a < b, we infer that (M mod a) mod b = M mod a, so the condition is equivalent to M mod a = (M mod b) mod a, i.e., M − (M mod b) is a multiple of a. We can iterate over all b and count factors of M − (M mod b) using a sieve, resulting in a Θ(N + M log N)-time algorithm.

N = 2304
M = 23498


def fast():
    npairs = 0
    nfactors = [1] * (M + 1)
    for b in range(2, N + 1):
        npairs += nfactors[M - M % b]
        for i in range(0, M + 1, b):
            nfactors[i] += 1
    return npairs


def naive():
    return sum((M % a) % b == (M % b) % a for b in range(2, N + 1) for a in range(1, b))


print(fast(), naive())
David Eisenstat
  • 64,237
  • 7
  • 60
  • 120
1

Think of it like x%mod(a) is same as x%mod(b) only condition a<b and if mod(b) is calculated, don't need to calculate mod(a) again if its already stored .

(n-1) is for all the pairs of 1's

for _ in range(int(input())):

    n,m=map(int,input().split())

    count=0

    dictitems=defaultdict(int)

    for i in range(2,n+1):

        rem=m%i

        count+=dictitems[rem]

        for j in range(rem,n+1,i):

            dictitems[j]+=1

    print(count+(n-1))

Ade_1
  • 1,480
  • 1
  • 6
  • 17
Jagdishwar
  • 21
  • 3
0

Your approach is a good start but takes exactly N * N iterations.

You can start with following improvements.

  1. sort the data

  2. Using 2 pointer approach with optimised search range for second pointer

for i in range(1, n+1):
    for j in range(i+1, n+1): # note j start at `i+1`
sam
  • 1,819
  • 1
  • 18
  • 30
  • 1
    it works and time is also below 1 sec.but it is partially accepted.all sub task is not fullfilled.by the way,thank you so much – Arshad Hossain May 11 '21 at 08:56