T(n)= T(n-sqrt(n))+ T(sqrt(n))+ 1

时间:2019-06-03 20:00:58

标签: big-o complexity-theory recurrence

如何解决这种复发? 归纳是获得答案的唯一方法吗?如果是这样,您如何猜测基本情况?

我的猜测是 O(登录),但我不确定如何解决。

1 个答案:

答案 0 :(得分:2)

重复关系为:

// Tail<T> pulls the first element off a tuple: Tail<[1,2,3]> is [2,3]
type Tail<T extends any[]> = ((...t: T) => void) extends ((
  h: any,
  ...r: infer R
) => void)
  ? R
  : never;
// Last<T> returns the last element of a tuple: Last<[1,2,3]> is 3
type Last<T extends any[]> = T[Exclude<keyof T, keyof Tail<T>>];

// OkayFunction<F> for a function F evaluates to F if the last argument
// is not a function, or never if the last argument is a function
type OkayFunction<F extends (...args: any) => any> = Last<
  Parameters<F>
> extends Function
  ? never
  : F;

// have withOptionalCallback return an overloaded function to make up for
// the lack of ability to push an optional element onto a tuple 
function withOptionalCallback<F extends (...args: any) => any>(
  f: F & OkayFunction<F>
): {
  (...args: Parameters<F>): void;
  (...args: Push<Parameters<F>, Callback<ReturnType<F>>>): void;
};
function withOptionalCallback(f: Function) {
  return function(...args: any[]) {
    const params = args.slice();
    let cb: Function = () => {};
    if (typeof params[params.length - 1] === "function") {
      cb = params.pop();
    }
    cb(f(...params));
  };
}

// make sure it works
const g2 = withOptionalCallback(f);
g2("Hello"); // okay
g2(123); // error, 123 is not a string

g2("Hello", n=>console.log(n-2)); // okay
g2("Hello", "oops"); // error, "oops" is not a Callback<number>;

function badF(x: string, y: (x: string)=>number) { return y(x); }
const cantDoThis = withOptionalCallback(badF) // error!
// Argument of type '(x: string, y: (x: string) => number) => number' 
// is not assignable to parameter of type 'never'.

我们可以写出一些术语:

T(1) = c
T(n) = T(n - sqrt(n)) + T(sqrt(n)) + 1

尝试一些条件后,它看起来肯定是线性的。我们可以猜出T(n)= k(c + 1)-1并尝试证明这一点。

基本情况:T(1)= c = 1(c + 1)-1 = c + 1-1 = c。已验证

归纳假设:假设所有n(包括k)的T(n)= n(c +1)-1

归纳步骤:显示T(k + 1)=(k + 1)(c + 1)-1。从循环中,我们有T(k + 1)= T(k + 1-sqrt(k + 1) ))+ T(sqrt(k + 1))+1。根据归纳假设,它等于(k + 1-sqrt(k + 1))(c +1)-1 + sqrt(k + 1) (c +1)-1 +1。根据需要,简化为(k + 1)(c + 1)-1-1 + 1 =(k +1)(c +1)-1。

因此,T(n)= n(c +1)-1,结果T(n)= O(n)。