整数n,是>=0或>=1 (f(0)是可选的)
以下序列中的n'th数,或直到并包含n'th数的序列。
(0),1,-1,-3,0,5,-1,-7,0,9,-1,-11,0,13,-1,-15,0,17,-1,-19,0,21,-1,-23,0,25,-1,-27,0,29,-1,-31,0,33,-1,-35,0,37,-1,-39,0,41,-1,-43,0,45,-1,-47,0,49,-1,-51,0,53,-1,-55,0,57,-1,-59,0,61,-1,-63,0,65,-1,-67,0,69,-1,-71,0,73,-1,-75,0,77,-1,-79,0,81,-1,-83,0,85,-1,-87,0,89,-1,-91,0,93,-1,-95,0,97,-1,-99这个序列是如何构建的?
f(n=0) = 0 (可选)
f(n=1) = f(0) + n或f(n=1) = 1
f(n=2) = f(1) - n
f(n=3) = f(2) * n
f(n=4) = f(3) / n
f(n=5) = f(4) + n
等。
或者用伪码:
function f(integer n){
Integer result = 0
Integer i = 1
Loop as long as i is smaller than or equal to n
{
if i modulo-4 is 1:
result = result plus i
if i modulo-4 is 2 instead:
result = result minus i
if i modulo-4 is 3 instead:
result = result multiplied with i
if i modulo-4 is 0 instead:
result = result integer/floor-divided with i
i = i plus 1
}
return result
}但是,正如您可能已经注意到的,序列中有两种模式:
0, ,-1, ,0, ,-1, ,0, ,-1, ,0, ,-1, ,0, ,-1, ,...
,1, ,-3, ,5, ,-7, ,9, ,-11, ,13, ,-15, ,17, ,-19,...因此,任何其他导致相同序列的方法当然也是完全好的。
f(0)对于0索引输入是可选的,如果您想包含它)。n'th号,或者整个序列向上并包含n'th数。(因此f(5)可以生成5或0,1,-1,-3,0,5。) 。n'th号的序列,则输出格式是灵活的。可以是列表/数组、逗号/空格/新行分隔字符串或打印到STDOUT,等等。/)是整数/地板除法,其舍入为0(而不是某些语言中的负无穷大)。n=100:之上的附加测试用例
Input Output
1000 0
100000 0
123 -123
1234 -1
12345 12345
123456 0发布于 2018-04-13 11:57:11
n=>[0,n,-1,-n][n&3]假设我们对4的n个倍数有以下关系。这些关系在序列的第一个项上得到了很小的验证。
f(n) = 0
f(n+1) = n+1
f(n+2) = -1
f(n+3) = -(n+3)设N=n+ 4,那么,根据定义:
f(N) = f(n+4) = f(n+3) // (n+4) = -(n+3) // (n+4) = 0
f(N+1) = f(n+5) = f(n+4) + (n+5) = 0 + (n+5) = N+1
f(N+2) = f(n+6) = f(n+5) - (n+6) = (n+5) - (n+6) = -1
f(N+3) = f(n+7) = f(n+6) * (n+7) = -1 * (n+7) = -(N+3)通过数学归纳法,证明了该关系适用于4的任意N倍数。
发布于 2018-04-13 11:43:28
输出nth号码
ÎD(®s)sè使用序列中的模式输出到N的数字列表
ÅÉāÉ·<*āÉ<‚øí˜使用N=7的示例
ÅÉ # List of odd numbers upto N
# STACK: [1,3,5,7]
ā # Enumerate 1-based
É # is odd?
# STACK: [1,3,5,7],[1,0,1,0]
·< # double and decrement
# STACK: [1,3,5,7],[1,-1,1,-1]
* # multiply
# STACK: [1,-3,5,-7]
āÉ< # enumerate, isOdd, decrement
# STACK: [1,-3,5,-7],[0,-1,0,-1]
‚ø # zip
# STACK: [[1, 0], [-3, -1], [5, 0], [-7, -1]]
í # reverse each
˜ # flatten
# RESULT: [0, 1, -1, -3, 0, 5, -1, -7]https://codegolf.stackexchange.com/questions/162101
复制相似问题