我有一个遵循特定逻辑的二进制序列,它以0和
开头nth term = sequence of (n-1)th term + 0 + inverse(reverse(n-1)th term)
例如:
0
0 + 0 + 1
001 + 0 + 011
0010011 + 0 + 0011011
在这里,我需要找出第k个序列的第n项。我的看法:
static int foo(long n, int k) { //n-th element (indexed from 0) in k-th sequence
long length = (2 << k) - 1; //computes 2^(k+1)-1
if(n == length/2) return 0;
if(n < length/2) return foo(n, k-1);
return 1 - foo(length - n - 1, k-1);
}
但是如果我尝试在第50个序列中计算2378421387489th元素,它在StackOverflow处失败。我该如何避免这种情况?
答案 0 :(得分:1)
你应该添加一些先决条件检查:
<td><a href="edit_teacher.php?edit=<?php echo $row['teach_id']; ?>"><button type="button"><span class="glyphicon glyphicon-edit" style="font-size: 20px; color: green;"></span></button></a></td>
<td><a href="delete_teach.php?del=<?php echo $row['teach_id']; ?>" onclick="return confirm('The Record will be Deleted....???');"><button type="button"><span class="glyphicon glyphicon-trash" style="font-size: 20px; color: #ac2925;" ></span></button></a></td>
您的功能的正确实现是:
static int foo(long n, int k) { //n-th element (indexed from 0) in k-th sequence
long length = (2 << k) - 1; //computes 2^(k+1)-1
if(n > length) throw new IllegalArgumentException("Out of bounds");
if(n == length/2) return 0;
if(n < length/2) return foo(n, k-1);
return 1 - foo(length - n - 1, k-1);
}
答案 1 :(得分:-1)
溢出错误(当子函数调用的数量很高时,这在递归程序中很常见)。 我个人会避免使用递归。
尝试将递归代码更改为循环并重新运行。