给定一个数字n,编写一个程序,找出最小的基本b ≥ 2,这样n是基b中的回文。例如,28的输入应该返回自28_{10} = 1001_3以来的基本3。虽然93在基本2和基5中都是回文,但是从2<5开始输出应该是2。
正整数n < 2^{31}。
返回最小的基b ≥ 2,以便n的基本b表示形式是回文。不要假定任何前导零。
样本(输入=>输出):
11 \to 10 32 \to 7 59 \to 4 111 \to 6
最短的代码获胜。
发布于 2014-05-22 06:27:06
~:x,2>{x\base.-1%=}?与GolfScript的方法不同,而不是丹尼斯‘。它避免了代价高昂的显式循环,有利于查找操作符。试着上网。
~:x # interpret and save input to variable x
,2> # make a candidate list 2 ... x-1 (note x-1 is the maximum possible base)
{ # {}? find the item on which the code block yields true
x\ # push x under the item under investigation
base # perform a base conversion
.-1% # make a copy and reverse it
= # compare reversed copy and original array
}? 发布于 2014-05-22 10:58:06
f=function(n){for(a=b='+1';a^a.split('').reverse().join('');a=n.toString(++b));return+b}f = function(n) {
for(a = b = '+1'; // This is not palindrome, but equals 1 so we have at least one iteration
a ^ a.split('').reverse().join(''); // test a is palindrome
a = n.toString(++b));
return+b
}发布于 2014-05-22 18:27:25
#.inv~(-.@-:|.@)(1+]^:)^:_&2解释:
#.inv~ --将左参数展开到右侧参数的基中。(-.@-:|.@) -如果展开是回文的,则返回0,否则返回1。(1+]^:) --如果我们返回1,则增加一个正确的参数,否则不采取任何行动。^:_ -重复上面的增量,直到它不采取任何行动。&2 -将正确的参数准备为2,使其成为一个参数的函数。示例:
#.inv~(-.@-:|.@)(1+]^:)^:_&2 (28)
3
#.inv~(-.@-:|.@)(1+]^:)^:_&2 every 93 11 32 59 111 NB. perform on every item
2 10 7 4 6
#.inv~(-.@-:|.@)(1+]^:)^:_&2 every 1234 2345 3456 4567 5678 6789
22 16 11 21 31 92https://codegolf.stackexchange.com/questions/28404
复制相似问题