存在一个方程,假设n
和x
是正的,
这表达了两个单调词之间的关系,其中一个是另一个的常见错误表述。许多人犯了一个简单的错误,把它们等同起来(即3x^2
和(3x)^2
)。
给定一个正整数i
,确定并返回以最小和作为数组[n, x]
的解n
和x
。对于领带,任何解决方案都是可以接受的。
62658722541234765
[15, 11]
202500
[4, 15]
524288
[8, 4]
33044255768277
[13, 9]
发布于 2016-09-17 03:33:56
感谢英里节省了2个字节,加上一整堆字节,我没有理由计算!
Last@Select[{n,(#/n)^(1/n)}~Table~{n,2Log@#},IntegerQ@*Last]&
使用所有可能的n值计算由对{n,x}组成的表,其中x= (i/n)^(1/n);只保留对应的x为整数的表;然后返回最大值为n的对。
在这里,“n的所有可能值”从1到2*ln(i)不等。这忽略了解{n,x} = {i,1},但这是可以的,因为如果这是最好的选择,那么解{n,x} = {1,i}就足够了。所以x永远不需要小于2,这意味着n*2^n≤i,并且所有这样的n都小于2*i(I)。
可以用微积分表明,在这种情况下使它们和最小化的对{n,x}与最大n的对{n,x}相同(不包括{i,1})。这就是为什么初始Last
足够好,可以找到最优对的原因。
发布于 2016-09-17 08:45:33
,[N:X]#>>==L(.rMtT;Lr.rMtT),M^:T*?,
在网上试试!
我们构造一个list [N, X]
,其中N >= X
,然后在给它赋值之后,我们尝试将[N, X]
和[X, N]
作为可能的输出。例如,如果N
被分配给3
,我们将通过回溯[3, 1]
、[1, 3]
、[3, 2]
、[2, 3]
、[3, 3]
和[3, 3]
进行测试。在此之后,下一个回溯步骤将发生在N
的值上,该值将转到4
等。
,[N:X] The list [N, X]
#> Both N and X are strictly positive
>= N >= X
=L Assign values to N and X, and L = [N, X]
( Either...
. Output = L
rM M is the reverse of the Output
tT T is the second element of M
; ...or...
Lr. Output is the reverse of L
rM M = L
tT T is the last element of M
),
M^ First element of M to the power of the second element of L (T)...
:T*?, ... times T is equal to the Input
发布于 2016-09-17 09:56:58
`T@XK:"@K@-@^*G=?3Mb~.
输出是按该顺序排列的x
、n
。
输入受到MATL的默认double
数据类型的限制,这种数据类型只能精确地表示2^53
的整数。这不包括第一个测试(尽管如此,它给出了正确的结果,但对于如此大的输入,这在一般情况下是不能保证的)。
在网上试试!
代码使用两个嵌套循环:
do...while
循环按递增顺序遍历所有可能的和n+x
。一旦找到解决方案,循环就会停止。这保证了我们用最小和输出解。for each
循环用该和测试所有n
和x
。当和与输入相重合时,内环退出,外环的循环条件设置为false
,从而使其也退出。注释代码:
` % Do...while
T % Push "true". Will be used as loop condition (possibly negated to exit loop)
@ % Push iteration index, say K, which represents n+x
XK % Copy that into clipboard K
: % Range [1 2 ... K]
" % For each
@ % Push loop variable (1, 2, ... K), which represents n
K@- % Compute x as K minus n
@ % Push n again
^* % Power, multiply. This gives n*x^n
G= % Does this equal the input?
? % If so
3M % Push the inputs of the third-last function, that is, x and n
b % Bubble up the "true" that is at the bottom of the stack
~ % Transform it into "false". This will exit the do...while loop
. % Break the for loop
% Implicitly end if
% Implicitly end for
% Implicitly end do...while
% Implicitly display
https://codegolf.stackexchange.com/questions/93582
复制相似问题