零和计数


25

编写一个程序或函数,如果n≥1,则返回的解数为±1±2±3±...±n = 0。

对于n = 6,没有解,所以答案为0。对于n = 4,有两个解,所以答案为2(两个解是1-2-3 + 4 = -1 + 2 + 3-4 = 0)。

这是OEIS序列A063865。一些示例输入/输出是:

n       a(n)
1       0
2       0
3       2
4       2
5       0
6       0
7       8
8       14
9       0
10      0
11      70
12      124
13      0
14      0
15      722
16      1314

以字节为单位的最短代码获胜。



1
@ManishKundu Hm,我想说这对我来说可能是一个可能的欺骗目标,只需在末尾加上“长度”,或者代替“按总和等于过滤”即可“求和然后计数”来解决这个问题。
暴民埃里克(Erik the Outgolfer)'18年

2
@EriktheOutgolfer我没有意识到这个挑战,但是答案可能是完全不同的,例如我的。
orlp

2
@ManishKundu我刚刚解释了这个挑战有何不同...
orlp

2
是的,我看到了。不幸的是,您无意中提出了自己的问题,但不应强迫您投反对票。
丹尼斯

Answers:






5

C(gcc),45 62 52 50字节

f(n,r){n=n?f(n-1,r+n)+f(n-1,r-n):!r;}F(n){f(n,0);}

凯文·克鲁伊森(Kevin Cruijssen)的Java 8 答案端口。

在这里在线尝试。

请注意,由于注释中建议的改进,该代码在使用clang编译时会产生未定义的行为,甚至无法正常工作。

感谢etene打高尔夫球3个字节。感谢Kevin Cruijssen再打 10个字节。多亏克里斯托夫(Christoph)打高尔夫球了另外2个字节。

非高尔夫版本:

f(n, r) { // recursive function - return type and parameter type are omitted, they default to int
    n = // instead of returning, we set n - dirty trick
        n ? // if n is not 0, recurse
        f(n-1,r+n) // +n
       +f(n-1,r-n) // -n
        !r; // else if r != 0 return 0 else return 1
}
F(n) { // function to start the recursion; again implicitly int(int)
    n = f(n, 0); // call the recursive function; this time we simply don't return
}

1
你可以通过替换剃掉3个字节r?0:1!r42位元组
etene '18

2
您似乎在这里接受其他输入以设置的初始值r,这是不允许的。
毛茸茸的

1
@etene很好,谢谢!
OOBalance

2
@KevinCruijssen更好,但第二个n=也没有必要:f(n,r){n=n?f(n-1,r+n)+f(n-1,r-n):!r;}F(n){f(n,0);}
Christoph

2
@OOBalance诀窍是二进制补码。这意味着,-x = ~x+1因此~x = -x-1
Christoph

5

05AB1E9 8字节

感谢Emigna节省了一个字节!

码:

LæO·sLO¢

使用05AB1E编码。在线尝试!

说明

L           # Create the list [1, 2, .., input]
 æ          # Compute the powerset of this list
  O         # Sum each list
   ·        # Double each element
    sLO     # Compute the sum of [1, 2, .., input]
       ¢    # Count the number of occurrences

4

MATL14 13字节

[la]Z^G:!Y*~s

感谢@Giuseppe节省了1个字节!

在线尝试!验证所有测试用例

说明

考虑n = 3一个例子。堆栈显示为上下颠倒,即最新显示在下方。

[la]   % Push array [1 -1]
       % STACK: [1 -1]
Z^     % Cartesian power with inplicit input n
       % STACK: [ 1  1  1
                  1  1 -1
                  1 -1  1
                  1 -1 -1
                 -1  1  1
                 -1  1 -1
                 -1 -1  1
                 -1 -1 -1]
G:     % Push n, range: gives [1 2 ... n]
       % STACK: [ 1  1  1
                  1  1 -1
                  1 -1  1
                  1 -1 -1
                 -1  1  1
                 -1  1 -1
                 -1 -1  1
                 -1 -1 -1],
                 [1  2  3]
!      % Transpose
       % STACK: [ 1  1  1
                  1  1 -1
                  1 -1  1
                  1 -1 -1
                 -1  1  1
                 -1  1 -1
                 -1 -1  1
                 -1 -1 -1],
                 [1
                  2
                  3]
Y*     % Matrix multiplication
       % STACK: [6
                 0
                 2
                -4
                 4
                -2
                 0
                -6]
~      % Logical negation
       % STACK: [0
                 1
                 0
                 0
                 0
                 0
                 1
                 0]
s      % Sum of vector. Implicit display
       % STACK: 2

4

果冻,8字节

ŒPS€ċÆṁ$

在线尝试!

怎么运行的

ŒPS€ċÆṁ$  Main link. Argument: n

ŒP        Take the powerset of [1, ..., n].
  S€      Take the sum of each subset.
       $  Combine the two links to the left into a monadic chain.
     Æṁ       Compute the median of the sums, i.e, (1 + ... + n)/2.
    ċ         Count the occurrences of the median.

3

Python 2,74个字节

def f(n):l=k=1;exec"l+=l<<n*k;k+=1;"*n;return(l>>n*n*-~n/4)%2**n*(~-n%4>1)

更有趣的提交,直接生成函数计算。


3

八度 (带有通信包),39字节

@(n)sum((2*de2bi(0:2^n-1)-1)*(1:n)'==0)

在线尝试!

说明:

取范围0 ... n ^ 2-1并将其转换为二进制。这给出了具有01的所有组合的矩阵。乘以2并减去1得到具有-1+1所有组合的矩阵。

1 ... n范围内的点积,得到±1±2 ...±n的所有组合。计算多少为零。

基本上相同,相同字节数:

@(n)nnz(~((2*de2bi(0:2^n-1)-1)*(1:n)'))


3

Python 2和3,50个字节

像大多数答案一样的递归方法:

f=lambda n,r=0:f(n-1,r+n)+f(n-1,r-n)if n else r==0

在线尝试

双递归调用占用太多字节...可能有一种简化它的方法。


3

Java 8,72 71 70字节

n->f(0,n)int f(int r,int n){return n>0?f(r+n,--n)+f(r+~n,n):r==0?1:0;}

@Arnauld的JavaScript(ES6)Answer的端口。
-2个字节,感谢@OlivierGrégoire

在线尝试。

说明:

n->                 // Method with integer parameter and integer return-type
  f(0,n)            //  Call the recursive method with 0 and this parameter

int f(int r,int n){ // Recursive method with integer as both two parameters and return-type
  return n>0?       //  If `n` is not 0 yet:
    f(r+n,--n)      //   Recursive call with `r+n` (and `n` lowered by 1 first with `--n`)
    +f(r+~n,n)      //   + Recursive call with `r-n` (and `n` also lowered by 1)
   :r==0?           //  Else-if `r` is 0
     1              //   Return 1
    :               //  Else:
     0;}            //   Return 0

3

Haskell,55个字节

一种计算所有这些和并检查有多少为零的简单方法。

f 0=[0]
f n=[(n+),(n-)]>>=(<$>f(n-1))
g x=sum[1|0<-f x]

在线尝试!

编辑:@ H.PWiz有一个更短,更优雅的解决方案,使用mapM



3

Brachylog,12个字节

⟦₁{{ṅ|}ᵐ+0}ᶜ

在线尝试!

说明

⟦₁               The range [1, …, Input]
  {       }ᶜ     Count the number of times the following predicate succeeds on that range:
   {  }ᵐ           Map for each element of the range:
    ṅ                Negate
     |               Or do nothing
        +0         The sum of the elements after the map is 0








1

Pyth,14 13字节

lf!s.nT*F_BRS

在这里尝试

说明

lf!s.nT*F_BRS
            SQ  Take the list [1, ..., <implicit input>].
         _BR    Get the pairs [[1, -1], [2, -2], ...].
       *F       Take the Cartesian product.
 f!s.nT         Find the ones where the flattened sum is 0.
l               Take the length.


1

Stax,9 个字节

è%é┐╬@₧╠¬

运行并调试

到目前为止 ,果冻打败的最短答案之一

我觉得明确检查哪些符号总和为零并不是很容易,所以我取幂集并检查幂集中有多少个集合的和为第n个三角数的一半。毫不奇怪,此方法与检查哪个符号总和为零的时间复杂度相同。

ASCII等效项:

RS{|+Hmx|+#

0

Pyth,10个字节

/mysdySQsS

在线尝试。或者,一次验证所有测试用例

说明:

/mysdySQsS    Implicit: Q=input()
      SQ      Generate range [1...Q]
     y        Generate powerset of above
 m            Map d in the above over...
  ysd         ... double the sum of d
        sS    Sum of range [1...Q] (final Q is implicit)
/             Count the matches (implicit output)

0

J,28个字节

(*>:){1j3#1+//.@(*/)/@,.=@i.

使用OEIS中的其他定义,其中a(n) = coefficient of x^(n(n+1)/4) in Product_{k=1..n} (1+x^k) if n = 0 or 3 mod 4 else a(n) = 0

在线尝试!

说明

(*>:){1j3#1+//.@(*/)/@,.=@i.  Input: n
                          i.  Range [0, n)
                        =     Self-Classify. Forms an identity matrix of order n
          1           ,.      Stitch. Prepend 1 to each row
                    /         Reduce using
                                Convolution
                 */               Product table
           +//.                   Sum along anti-diagonals
      1j3#                    Copy each once, padding with 3 zeroes after
     {                        Index at n*(n+1)
  >:                            Increment n
 *                              Times n

0

外壳,9个字节

#½Σḣ¹mΣṖḣ

在线尝试!

说明

#½Σḣ¹mΣṖḣ  Implicit input
        ḣ  [1..input]
       Ṗ   Powerset
     mΣ    Sum each list
#          Count occurrence of
   ḣ¹        [1..input]
 ½Σ          Half of sum

0

Gol> <>,26个字节

:IFPlMF2K+}:@-}||0lMF$z+|h

在线尝试!从1到16运行测试用例!

怎么运行的

:IFPlMF2K+}:@-}||0lMF$z+|h

Main outer loop
:IFPlMF ...... ||
:        Duplicate top; effectively generate two explicit zeroes
         Top is the loop counter `i`;
         the rest is the generated 2**i sums
 I       Take input as number
  F ........... |  Pop n and loop n times
   P     i++
    lM   Push stack length - 1, which is 2**(i-1)
      F ...... |   Loop 2**(i-1) times

Main inner loop: generate +i and -i from 2**(i-1) previous sums
2K+}:@-}
          Stack: [... x i]
2K        [... x i x i]    Copy top two
  +}      [x+i ... x i]    Add top two and move to the bottom
    :@    [x+i ... i i x]  Duplicate top and rotate top 3
      -}  [i-x x+i ... i]  Subtract and move to the bottom

Counting zeroes
0lMF$z+|h
0lM        Push zero (zero count) and 2**n (loop count)
   F...|   Loop 2**n times
    $z+    Swap top two; Take logical not; add to the count
        h  Print top as number and halt
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.