打印数字根


19

这与My Word可以打败您的Word有所不同,因为它不那么复杂,只需要您对其进行计算,而不进行比较。

要找到数字根,请获取一个数字的所有数字,将它们相加,然后重复直到获得一个数字。例如,如果数字是12345,你会增加1234,和5,越来越15。然后,您将添加15,然后给您6

你的任务

通过STDIN给定整数N(0 <= N <= 10000),请打印N的数字根。

测试用例

1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7

请记住,这是,所以字节数最少的代码将获胜。


1
也许是这项挑战的子任务。
nimi

3
非常密切相关的这一挑战 ......也许足够近的欺骗。
AdmBorkBork,2016年

8
说时请更精确number。尤其是。必须0支持输入吗?
Ton Hospel '16

2
@TimmyD我认为这是一个更加干净的挑战,无需在整数转换中添加字母,为两个值计算函数并包括文字STALEMATE。最好关闭另一个作为此操作的副本。
马丁·恩德

3
@MartinEnder我撤回了我的近距离投票,我认为结束一个好的挑战作为对另一个更复杂挑战的欺骗是不公平的。
暴民埃里克(Erik the Outgolfer)'16年

Answers:



17

果冻7 5 4 3 个字节

ḃ9Ṫ

TryItOnline!所有测试用例

怎么样?

数字根已知服从式(N-1)%9 + 1。
这与双射基数9中的最后一位数字相同
(并且由于实现该功能0ḃ9=[]并且可以[]Ṫ=0处理零的边沿情况)。

ḃ9Ṫ - Main link: n
ḃ9  - convert to bijective base 9 digits (a list)
  Ṫ - tail (get the last digit)


6

MATL,3个字节

9X\

在线尝试!

许多(现在已删除的答案)尝试使用模9来获得结果。这是一个很好的捷径,但不幸的是不适用于9的倍数。MATL具有对interval取模的功能[1, n]。使用此模,我们得到1 % 3 == 1, 2 % 3 == 2, 3 % 3 == 3, 4 % 3 == 1,等等。此答案使用此自定义模简单地将输入模数取为9。


6

Mathematica,27个 11字节

Mod[#,9,1]&

Mathematica Mod使用第三个参数作为所得模数范围的偏移量。这样避免了递减输入和递增输出。


6

Python,16个 20字节

+4个字节来处理零的边缘情况。

lambda n:n and~-n%9+1

代表


1
哇。这很容易,可以移植到任何语言。您甚至可以~-input()%9+1
Karl Napf

1
不幸的是,它不适用于0。
Emigna

@KarlNapf不需要print吗?
乔纳森·艾伦

@JonathanAllan Ah,可能。我只是在REPL环境中进行了测试,然后做到了。
Karl Napf

1
@尝试进行编辑的匿名用户-它实际上已经破坏了代码(在0结果中输入9而不是0,这是n and代码部分满足的要求),此外,它还会算作19个字节而不是13个字节(因为print必须对和空间进行计数)。
乔纳森·艾伦

4

朱莉娅,12个字节

!n=mod1(n,9)

要么

n->mod1(n,9)

mod1mod映射到范围[1, n]而不是的替代方法[0, n)


4

PHP,15字节

<?=--$argn%9+1;

先前版本PHP,55字节

$n=$argn;while($n>9)$n=array_sum(Str_split($n));echo$n;

我到底是怎么做到的!
CT14.IT

@ CT14.IT如果您愿意,我可以删除此帖子。你删除的帖子WS1分钟早,你只有忘记while循环
约尔格Hülsermann

不,删除的答案是错误的,因为我没有正确阅读该问题的开头,我没有尝试对所生成的数字求和
CT14.IT 16-10-27

2
您可以添加其他答案的把戏<?=--$argv[1]%9+1?>
Crypto

3

Haskell,35 34字节

until(<10)$sum.map(read.pure).show

在Ideone上尝试。

说明:

until(<10)$sum.map(read.pure).show
                              show  -- convert int to string
               map(         ).      -- turn each char (digit) into
                        pure        --    a string 
                   read.            --    and then a number
           sum.                     -- sum up the list of numbers
until(<10)$                         -- repeat until the result is < 10

3

Perl,15个字节

包括+2 -lp

在STDIN上输入

root.pl <<< 123

root.pl

#!/usr/bin/perl -lp
$_&&=~-$_%9+1

这是一个已经在许多语言中给出的无聊的解决方案,但至少该版本支持0

进行真正的重复加法(尽管以另一种顺序)更有趣,实际上仅长了1个字节:

#!/usr/bin/perl -p
s%%$_+=chop%reg

3

R,72 67 29字节

编辑:感谢@rturnbull削减了两个字节。

n=scan();`if`(n%%9|!n,n%%9,9)

我最近了解到ifelse可以用替换为`if`,而具有相同的行为,这可以节省几个字节。
rturnbull

@rturnbull我一直想知道` if` 是如何工作的。您能举个例子还是将其添加到 打高尔夫球的技巧中?
Billywob

理解它的最简单方法是它是非向量化的ifelse。在这种情况下,`if`(n%%9|!n,n%%9,9)提供与您发布的代码相同的行为。据我所知,这种行为是没有记载的!我将在提示线程中添加评论。
rturnbull

3

视网膜,7字节

{`.
*
.

在线尝试!

我看到了许多数学解决方案,但在Retina中,简单的方法似乎是最好的方法。

说明

{`使整个程序循环运行,直到字符串不再更改为止。循环包括两个阶段:

.
*

将每个数字转换为一元。

.

计算字符数(=将一进制数字转换为十进制)。

之所以可行,是因为将每个数字转换为一进制,且数字之间没有分隔符,将创建一个等于所有数字之和的一元数字。


2

Brachylog,9个字节

#0|@e+:0&

在线尝试!

说明

#0            Input = Output = a digit
  |           OR
   @e         Split the input into a list of digits
     +        Sum
      :0&     Call this predicate recursively

替代方法,11个字节

:I:{@ e +} i#0

这个使用元谓词i - Iterate来调用输入中I谓词的{@e+}时间。这将尝试I从from 0到infinity的值,直到得到它为止,以便of的输出i为单个数字才#0成立。


2

JavaScript(ES6),41 38字节

由于Bassdrop Cumberwubwubwub,节省了3个字节

获取并返回一个字符串。

f=s=>s[1]?f(''+eval([...s].join`+`)):s

测试用例


4
您可以更改s.split``[...s]
Bassdrop Cumberwubwubwub

2

CJam19 13字节

r{:~:+_s\9>}g

口译员

说明:

r{:~:+_s\9>}g Code
r             Get token
 {:~:+_s\9>}  Block: :~:+_s\9>
   ~          Eval
  :           Map
     +        Add
    :         Map
      _       Duplicate
       s      Convert to string
        \     Swap
         9    9
          >   Greater than
            g Do while (pop)

多亏了8478(马丁·恩德)的-6个字节。


CJam,6个字节

ri(9%)

8478(Martin Ender)建议。口译员

我当时在想,但马丁在我之前就知道了。说明:

ri(9%) Code
r      Get token
 i     Convert to integer
  (    Decrement
   9   9
    %  Modulo
     ) Increment

Single-command map and reduce can both be written with prefix :, so you can do :~:+. It also doesn't hurt to run the block at least once so you can use a g loop instead of a w loop.
Martin Ender

@MartinEnder r{_,1>}{:~:+`}w works, but I don't know how on earth am I supposed to use g here.
Erik the Outgolfer

E.g. like this: r{:~:+_s\9>}g (of course the closed form solution ri(9%) is much shorter.
Martin Ender

@MartinEnder Oh gawd, for real now, I'm such a beginner...
Erik the Outgolfer

The second one doesn't work on multiples of 9
ThePlasmaRailgun

2

Java 7, 63 bytes

int f(int n){int s=0;for(;n>0;n/=10)s+=n%10;return s>9?f(s):s;}

Recursive function which just gets digits with mod/div. Nothing fancy.

Cheap port

of Jonathan Allan's would be a measly 28 bytes:

int f(int n){return~-n%9+1;}

1

Python 2, 54 51 bytes

i=input()
while~-len(i):i=`sum(map(int,i))`
print i 

Thanks to Oliver and Karl Napf for helping me save 3 bytes


You can change while len(i)>1 to while~-len(i) to save one byte.
Oliver Ni

I think you can omit the ticks around input() and force the input the be enclosed in quotes to save 2 bytes.
Karl Napf

@KarlNapf I don't think you can do this when the input is an integer.
Erik the Outgolfer

@EriktheGolfer, the op said that the input can be taken as a string
Daniel

1

Python, 45 bytes

f=lambda x:x[1:]and f(`sum(map(int,x))`)or x

Takes the argument as a string.



1

C, 64 29 bytes

C port from Jonathan Allan's answer (with special case 0).

f(i){return i>0?~-i%9+1:0;}

Previous 64 byte code:

q(i){return i>9?i%10+q(i/10):i;}
f(i){i=q(i);return i>9?f(i):i;}

q takes the cross sum and f repeats taking the cross sum until a single digit.


1

Retina, 15 bytes

.+
$*
1{9}\B

1

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

.+
$*

Convert input to unary.

(1{9})*\B

Take 1-based modulo by removing nines that have at least one more character after them.

1

Count the remaining number of 1s to convert back to decimal.


1

Perl 6, 29 bytes

{($_,*.comb.sum...10>*)[*-1]}

Expanded:

{ # bare block lambda with implicit parameter 「$_」
  ( # generate a sequence

    $_,         # starting with the input
    *.comb.sum  # Whatever lambda that splits into digits, and finds sum
    ...         # keep doing that
    10 > *      # until it is less than 10

  )[ * - 1 ] # get the last value
}

1

Factor, 24

Smart, mathy answer.

[ neg bitnot 9 mod 1 + ]

63 for dumb iterative solution:

[ [ dup 9 > ] [ number>string >array [ 48 - ] map sum ] while ]

1

Labyrinth, 8 bytes

?(_9%)!@

using the equation (n-1)%9+1:

  • ? reads the input as decimal and pushes it to the stack
  • ( decrements the top of the stack
  • _ pushes a zero onto the top of the stack
  • 9 push the top of the stack popped times 10 the digit (in this case, 9)
  • % pops y, pops x, pushes x%y
  • ) increments the top of the stack
  • ! pops the top of the stack and out puts it as a decimal string
  • @ terminates the program

1

Pyth - 7 4 6 7 bytes

Not the best one, but still beats a decent amount of answers:

|ejQ9 9

Like the previous version, but handling also cases of multiples of 9, using logical or.


This version fails the 45 testcase:

ejQ9

Explanation:

 jQ9  -> converting the input to base 9
e     -> taking the last digit

Try it here

Try the previous version here!


Previous solutions:

&Qh%tQ9

Explanation:

    tQ    -> tail: Q-1
   %tQ9   -> Modulo: (Q-1)%9
  h%tQ9   -> head: (Q-1)%9+1
&Qh%tQ9   -> Logical 'and' - takes the first null value. If Q is 0 - returns zero, otherwise returns the (Q-1)%9+1 expression result

You're invited to try it here!


Your 4-byte version fails test case 45.
Dennis

Won't this give 0 for multiples of 9?
xnor

Yeah, I just noticed it. Will do some fixing there. Apparently, jQ9 doesn't act like Jelly's ḃ9 :-P
Yotam Salmon


1

Hexagony, 19 15 bytes

.?<9{(/>!@!/)%' 

More Readable:

  . ? < 
 9 { ( /
> ! @ ! / 
 ) % ' .
  . . . 

Try it online!

-3 bytes by taking a different approach, making the 0 edge case trivial.
-1 byte by fixing 0 edge case bug

Using the formula ((n-1) mod 9) + 1 like a lot of other solutions aswell.


1

K (oK), 9 bytes

Solution:

(+/.:'$)/

Try it online!

Explanation:

Super straightforward. Break number into digits and sum up - do this until the result converges:

(+/.:'$)/ / the solution
(      )/ / do this until result converges
      $   / string, 1234 => "1234"
   .:'    / value each, "1234" => 1 2 3 4
 +/       / sum over, 1 2 3 4 => 10

1
In my implementation of k I made x\y encode y in base x with as many digits as necessary, so it's slightly shorter: (+/10\)/
ngn

Nice. In the newer versions of kdb+ (I think from 3.4 and up) you can do 10\:.. but not in oK - and .:'$ is the same number of bytes - so I went with that :)
streetster

oK uses \ and requires a list on the left: `(,10)`
ngn

Indeed, your implementation adds "as many digits as necessary", which is what you get from \: in kdb+ (3.4+), but for oK I'd need to know how many 10s to put in my list.
streetster

1

Keg, 6 bytes(SBCS on Keg wiki)

¿;9%1+

Explanation:

¿#      Take implicit input
 ;9%1+# Digital Root Formula
# Implicit output

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.