简体   繁体   English

脚本的复杂性(找到一对具有相同余数的整数)

[英]Complexity of the script (finding a pair of integers which have the same remainder in modulo)

I am trying to find a pair (x,y) in A such that xy = 0 (mod n) where inputs are a positive integer n, a set A of m nonnegative integers and m > n.我试图在 A 中找到一对 (x,y),使得 xy = 0 (mod n),其中输入为正 integer n,一组由 m 个非负整数和 m > n 组成的 A。 To run the code below I took an m and n just for the sake of running an example.为了运行下面的代码,我拿了一个 m 和 n 只是为了运行一个例子。

Below is the script I have written.下面是我写的脚本。

What is the run time complexity in terms of n and m ?就 n 和 m 而言,运行时间复杂度是多少? --> Would it be O(N)? --> 会是 O(N) 吗? The main loop runs as much as the length of A, which is of length m.主循环与 A 的长度一样多,长度为 m。 I suppose the question is asking me to discuss in terms of m and n , but I am not sure what there is to say about n?我想问题是要我讨论m 和 n ,但我不确定关于 n 有什么要说的?

What would be the run time complexity if n is a constant ?如果 n 是常数,运行时间复杂度是多少? --> So, this is asked but isn't na constant anyway? --> 所以,这被问到了,但不是一直不变吗? I am a bit confused, the question says "inputs are a positive integer n..."我有点困惑,问题是“输入是正的 integer n...”

def find_equal_pair_mod_n(n, A):
  assert len(A) > n

  X = [-1] * n
  print(X)

  for i in range(len(A)-1,-1,-1) :  #loop backwards
    print(i)
    a = A[i]
    print(a)
    print(len(A))
    A.pop(i)
    r = a % n

    if X[r] == -1:
      X[r] = a
    else:
     return(X[r], a)

Short answer简短的回答

  1. "What is the run time complexity in terms of n and m ?". “就nm而言,运行时间复杂度是多少?”。 The correct answer is O(n) .正确答案是O(n)
  2. "What would be the run time complexity if n is a constant?". “如果n是常数,运行时间复杂度是多少?”。 The correct answer is O(1) .正确答案是O(1)

Explanation解释

  1. When you iterate over your loop, you can't do more than n + 1 iterations, because there are only n different remainders when divided by n .当你迭代你的循环时,你不能做超过n + 1次迭代,因为除以n时只有n不同的余数。 So you definitely find the answer in n + 1 or fewer iterations.所以你肯定会在n + 1次或更少的迭代中找到答案。
  2. If n is constant, you are still need n + 1 or fewer iterations to find the answer, so you need a constant time to solve your problem.如果n是常数,你仍然需要n + 1次或更少的迭代来找到答案,所以你需要一个常数时间来解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM