math - 如何在mathematica中定义使用复杂递归关系的函数?

标签 math wolfram-mathematica discrete-mathematics mathematica-8

我正在尝试编写一个小脚本来计算整数序列。我试图用代码编写的函数是黑板上的一个函数,a(n)。问题是我期望我在脚本中定义的函数 h(n) 给出一个数字作为结果,但它给出了其他东西:对于 h(2) 它给出 ArgMax[{p, HarmonicNumber[p] <= 1}, p, Integers]我该如何纠正这个问题? (你必须明白,我绝不是一名程序员,对mathematica也不太了解。提前谢谢。 我写的脚本是这样的:

    h[n_] := (ArgMax[{p, 
      Sum[1/s, {s, 1 + Sum[h[k], {k, 1, (n - 1)}], p}] <= 1}, p, 
     Integers]) - Sum[h[k], {k, 1, (n - 1)}]; h[1] = 1;

Image of the definition written by hand a(n)=(maximum p such that the sum from s equals r to p is less or equal than one)-r+1, where r=1+the sum from k=1 to (n-1) of a(k), and a(1)=1

PD:那些看起来像v的字母是r。抱歉。

最佳答案

a[1] = 1;

a[n_] := Module[{sum = 0},
  r = 1 + Sum[a[k], {k, n - 1}];
  x = r;
  While[sum <= 1, sum += 1/x++];
  p = x - 2;
  p - r + 1]

Table[a[n], {n, 6}]

{1, 2, 6, 16, 43, 117}

a[4] 的结果是 16 而不是 14。

举个例子,当n = 4

r = 1 + Sum[a[k], {k, 4 - 1}]

  = 1 + a[1] + a[2] + a[3]       (* refer to established results for a[n] *)

  = 1 +  1  +  2  +  6  =  10

sum = 0;
x = r;
While[sum <= 1, sum += 1/x++];
p = x - 2;
p - r + 1

16

或者其他形式

Total[Table[1/s, {s, 10, 25}]] <= 1   (* True *)

p - r + 1 = 25 - 10 + 1 = 16

使用memoisation ,正如奥杰拉德提到的

Clear[a]

a[1] = 1;

a[n_] := a[n] = Module[{sum = 0},
   r = 1 + Sum[a[k], {k, n - 1}];
   x = r;
   While[sum <= 1, sum += 1/x++];
   p = x - 2;
   p - r + 1]

仅将后续运行时间减少9秒

Timing[Table[a[n], {n, 14}]]

{40.8906, {1, 2, 6, 16, 43, 117, 318, 865, 2351, 6391, 17372, 47222, 128363, 348927}}

关于math - 如何在mathematica中定义使用复杂递归关系的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60196754/

相关文章:

mysql - 计算最低距离点GeoJSON + Mysql + Node

recursion - 在 Mathematica 中,为什么递归函数中的替换不会终止?

plot - Mathematica 分段函数错误的绘图渲染

java - 用Java实现概率分布函数

algorithm - 哪个算法分配类次(离散优化问题)

algorithm - 寻找 Big-O、Omega 和 theta

math - 术语 "BODMAS"是什么意思?

c - 求和对于 3 的幂是正确的,但除此之外

c - C中具有3个变量的线性方程

count - Mathematica 中的列联表