title: Print this sequence I just made up

text:
# Question
Title: Print this sequence I just made up
To get this sequence I just made up, which will subsequently be referred to as TSIJMU, consider the harmonic series:

\\$ \frac{1}{2} + \frac{1}{3} + \frac{1}{4} ...\\$

But what if you only add a term if it doesn't make the sum so far over 1, and otherwise subtract? Let's see an example here, starting at \\$\frac{1}{2}\\$:

Sum so far: 0, term: \\$ \frac{1}{2} \\$

\\$ 0 + \frac{1}{2} = \frac{1}{2}\\$, which is less than 1,so we add.

Sum so far: \\$ \frac{1}{2} \\$, term: \\$ \frac{1}{3} \\$

\\$ \frac{1}{3} + \frac{1}{2} = \frac{5}{6}\\$, which is less than 1,so we add.

Sum so far: \\$ \frac{5}{6} \\$, term: \\$ \frac{1}{4} \\$

\\$ \frac{1}{4} + \frac{5}{6} = \frac{13}{12}\\$, which is more than 1,so we subtract, yielding \\$\frac{7}{12}\\$.

If you do this forever, TSIJMU is the sequence of integers that are *added* when doing this. This goes 2,3,5,6,8, etc.

# Rules

Your code **must not** fail due to floating point errors. As pointed out by Arnauld, this means your code *may* fail due to integer overflow errors. If this is the case, please provide a version which works for arbitrary input size.

As with all challenges, there are three ways you can output:

* Take a number \\$n\\$ and return the nth item of TSIJMU
* Take a number \\$n\\$ and return the first n items of TSIJMU
* Print TSIJMU infinitely.

# Scoring

This is , shortest wins!

# Testcases

These are 0-indexed, but you can take 1-indexed.

```
0 => 2
3 => 6
9 => 17
25 => 48
58 => 113
90 => 177
156 => 308
352 => 700
479 => 953

```

As requested by Bubbler, the first 20 terms are:

```
2,3,5,6,8,10,12,13,15,17,19,21,23,25,27,29,31,33,34,36

```

# Answer
# Python 3.8, 54 bytes

*-1 byte thanks to @ovs*
*-4 bytes thanks to @att*

Outputs the sequence indefinitely.

```
a=b=n=2
while a:=a*n+[b,-b][a*n>b!=print(n)]:b*=n;n+=1

```

Try it online!

Although the code is heavily golfed, the idea is a straightforward implementation. `a` and `b` are the numerator and denominator of the current fraction. To add two fractions, we can use a simple formula: `a/b + c/d => (ad + cb) / bd`.
> 10 votes

# Answer
# Husk, 13 bytes

```
W<Goḟε§e+≠1İ\

```

Try it online!

An infinite list.

woo, it works.

-2 bytes from ovs.

-4 bytes from Dominic Van Essen.

## Explanation

```
Wo<0-Goḟε§e+`-1İ\
              1İ\ [1/2,1/3,1/4...
      Go      1   scan with 1 as intial value
         §e+`-    [a+b,a-b]
       ḟε         first element <=1
Wo                indices of pairs where
    -             difference is
  <0              < 0 (negative)

```
> 7 votes

# Answer
# Raku, 45 bytes

```
2.FatRat...{($!+=1/$_)>1??($!-=2/$_)!!.say}&1

```

Try it online!

Full program that outputs the sequence infinitely.
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~35~~ 34 bytes

```
#0[#+1/If[++i#>1,-Echo@i,i]]&[i=1]

```

Try it online!

Outputs the sequence indefinitely (up to `$IterationLimit`, 4096 by default).

Subtracts terms from 1 instead of adding from 0.

---

Without overriding `$IterationLimit`, **40 bytes**:

```
i=0;Do[i+=1/If[i>1/j,-Echo@j,j],{j,∞}]

```

Try it online!
> 5 votes

# Answer
# , ~~59~~ 58 bytes

*Edit: -1 byte thanks to emanresu A*

```
c=1
repeat`if`((F=F*(c=c+1)+T)>(T=T*c),F<-F-2*T/c,show(c))

```

Try it online!

Prints the sequence until it reaches the TIO output limit.

The numerator & denominator of the fraction so far are stored in `F` and `T` respectively. These won't error when they get too large, but  will assign them as `Inf`, beyond which point every integer will be (incorrectly) output, since `Inf>Inf` is evaluated as `FALSE`.

A non-overflowing version, using **+GMP** to handle large integers, is 93 bytes (the  version installed on TIO seems to give an error, so here is a link to a working version on rdrr.io, with `repeat` exchanged for `while(c<100)` to force output).
> 5 votes

# Answer
# Python 3, 78 bytes

```
from fractions import*
v=i=Fraction(1)
while 1:i+=1;v-=(v>1/i!=print(i)or-1)/i

```

Try it online!

-8 bytes thanks to ovs
-1 byte thanks to Jo King (the number can't be exactly 1, also thanks to Bubbler for the pseudo-proof of this)
-2 bytes thanks to att
> 2 votes

# Answer
# Stax, 19 bytes

```
«efy}á╤2╧8ßÇæ→╔y¬µ!

```

Run and debug it

Making a husk answer for this turned out to be very difficult. Here's a stack based one for the moment.
> 2 votes

# Answer
# 05AB1E `--no-lazy`, ~~20~~ 19 bytes

-1 byte thanks to Kevin Cruijssen!

```
λN*N<!©+DN!‹iN,ë®·-

```

Try it online!

There is no builtin fraction type, so everything is integers. (Ab)uses the recursive environment `λ` as an infinite loop that starts the iteration counter `N` at 1 and pushes a `1` to the stack initially.

```
λ                   # recursive environment
                    # generate infinite sequence of sums starting with a(0)=1
                    # pushes the last value to the stack, lets call this x
 N*                 # push N*x
    N<!©            # calculate (N-1)! and store a copy of the result in the register
        +D          # calculate N*x + (N-1)! and make a copy of the result
          N!‹       # is N*x + (N-1)! < N! ?
             iN,    # if so, N*x + (N-1)! / N! < 1 and print N
             ë®·-   # otherwise subtract (N-1)!*2 to get N*x - (N-1)!

```
> 2 votes

# Answer
# Perl 5, 42 bytes

This prints TSIJMU infinitely:

```
$i=1;1while$s+=1/++$i*($s+1/$i<1?say$i:-1)

```

Try it online!

...or until Try It Online reaches its limit of 128 KiB of output. Exploits that `say$i` prints that sequence number and then returns 1.

This is seven bytes longer and takes *n* from stdin:

```
$i=1;$s+=1/++$i*($s+1/$i<1?$_--&&say$i:-1)while$_

```

Try it online!
> 2 votes

# Answer
# JavaScript (with `alert`), 52 bytes

```
for(p=q=i=1n;;p*=i++)q*=i,p*i-p>q?alert(i,q+=p):q-=p

```

Try it online!
> 1 votes

# Answer
# Ly, 47 bytes

```
02s>n[<1f/+1G:![p:lu' o>,<]p[p1l/2*-0]pl`s>]>

```

Try it online!

```
02s>n[<1f/+1G:![p:lu' o>,<]p[p1l/2*-0]pl`s>]>
02                                            # Init stack w/ "0" (sum) "2" (divisor)
  s>                                          # Stash the divisor, change to iterator stack
    n                                         # Read number of output items "N" from STDIN
     [                 >,<                >]  # Loop, iterates until "N" is 0
      <                                       # Switch to accumulator stack
       1f/+                                   # Calculate "(1/divisor)+accumulator"
           1G:                                # Compare "accumulator>=1", duplicate answer
              ![p:        ]p                  # If-then, runs if "accumulator<1"
                  lu' o                       # Load the divisor, print as num, add " "
                       >,<                    # Switch to iterator stack, decr, switch back
                            [p      o]p       # If-then, runs if "accumulator>1"
                              1l/2*-          # Calc "2*(1/divisor)" and subtract
                                       l`s    # Increment divisor, stash it
                                            > # Switch to empty stack to suppress printing

```
> 1 votes

# Answer
# Charcoal, 51 bytes

```
Ｎθ≔¹η≔⁰ζ≔¹εＷ‹Ｌυθ«≦⊕ε≧×εζ¿›ζ×η⊖ε≧⁻ηζ«≧⁺ηζ⊞υε»≧×εη»Ｉυ

```

Try it online! Link is to verbose version of code. Outputs the first `n` terms. Explanation:

```
Ｎθ

```

Input `n`.

```
≔¹η≔⁰ζ≔¹ε

```

Start with a running total of `0/1` and the last fraction as `1/1`.

```
Ｗ‹Ｌυθ«

```

Repeat until enough terms have been collected.

```
≦⊕ε

```

Increment the denominator to get the next unit fraction.

```
≧×εζ

```

Multiply the running total by the denominator.

```
¿›ζ×η⊖ε≧⁻ηζ

```

If incrementing the running total would make it exceed the denominator then decrement it.

```
«≧⁺ηζ⊞υε»

```

Otherwise increment it and push the denominator to the list of results.

```
≧×εη

```

Divide the running total by the denominator.

```
»Ｉυ

```

Print the found terms.
> 1 votes

# Answer
# Japt v2.0a0, 29 bytes

Just ... hideous!

```
@¶Xõ!÷1 åÈ+Y§1©X+YªnXÃäÎèÉ}a2

```

Try it
> 1 votes

# Answer
# Zephyr, 108 bytes

```
set s to 0
set i to 2
while 1=1
if(s+(/i))<1
set s to(/i)+s
print i
else
set s to s-(/i)
end if
inc i
repeat

```

Outputs infinitely. Try it online!

Implements the spec directly, using Zephyr's built-in rational numbers. Here it is ungolfed:

```
set sum to 0
set i to 2
while true
    if (sum + (/i)) < 1
        set sum to sum + (/i)
        print i
    else
        set sum to sum - (/i)
    end if
    inc i
repeat

```
> 1 votes

# Answer
# Pip, 26 bytes

```
Wt*:oYt*o>y*Uo?t+y*Poy*o-t

```

Outputs infinitely. Try it here! Or, here's a 27-byte equivalent in Pip Classic: Try it online!

### Explanation

Pip doesn't have rational numbers, so we'll use integer math instead. We store the numerator of the running sum in `y` (initially `""`, which evaluates to 0 in a numeric context); the denominator in `t` (initially `10`, but any denominator greater than 0 will do, since the numerator is initially 0); and the index in `o` (initially `1`). Each time through the loop, we want to:

* Increment \\$o\\$
* Test whether \\$\frac y t + \frac 1 o \lt 1\\$
    + If so, output \\$o\\$ and add \\$\frac 1 o\\$ to \\$\frac y t\\$
    + If not, subtract \\$\frac 1 o\\$ from \\$\frac y t\\$

For the test, observe that

$$ \frac y t + \frac 1 o \lt 1 \\ \frac{y \cdot o + t}{t \cdot o} \lt 1 \\ y \cdot o + t \lt t \cdot o \\ y \cdot o \lt t \cdot (o - 1) $$

We can combine this expression with the increment of \\$o\\$ by calculating \\$t \cdot o\\$ first, then incrementing \\$o\\$, then calculating \\$y \cdot o\\$.

For the update, we need

$$ y := y \cdot o \pm t \\ t := t \cdot o $$

Observing that `t*:o` is always truthy, does not depend on the value of `y`, and is a no-op if executed before the first time through the loop, we can use it as the while-loop header.

```
Wt*:oYt*o>y*Uo?t+y*Poy*o-t
                            t is 10, o is 1, y is "" (implicit)
 t*:o                       Multiply t by o and assign the result back to t
W                           and loop while the result is truthy (non-zero):
      t*o>                   Is t*o greater than
            Uo               o, incremented
          y*                 times y?
              ?              If so:
                   Po         Print o
               t+y*           and calculate t+y*o
                             Else:
                     y*o-t    Calculate y*o-t
     Y                       Set y to the calculated value

```
> 1 votes

# Answer
# C (GCC), 75 bytes

```
n,d,i,j;s(a){for(n=i=1,d=j=2;a/i;n/d?n-=2*d/j:++i)n=n*++j+d,d*=j;return j;}

```

Try it online!

Overflows when the input is greater than 8.

How it works:

```
// n is the numerator, d the denominator, i the amount of numbers that have been added and j the denominator of the fraction that is supposed to be added.
n,d,i,j;
s(a)
{
    // The update statement of the for loop is moved to the end of the loop body for clearness (it's executed at the end of the loop anyways).
    // a / i is equivalent to a >= i, so we loop until i is greater than a
    for(n = i = 1, d = j = 2; a / i;)
        // Both n and d are multiplied by j, and the previous value of d is added to n.
        // The new fraction is (n*j + d) / (d*j).
        // (n*j)/(d*j) = n/d, so what's actually added to the fraction is d/(d*j), which can be rewritten as 1/j.
        n = n * ++j + d,
        d *= j,

        // n / d is non-zero iff n >= d, and n >= d iff n/d >= 1
        // If n/d >= 1, subtract what was previously added to n, twice.
        // Otherwise, increment i
        n / d ? n -= 2 * d / j : ++i;
    return j;
}

```

---

This 70-byte version also seems to work, although I'm not sure if it always does:

```
n,d,i,j;s(a){for(n=i=1,d=j=2;a/i;n/d?n-=2*d/j:++i)n=n*++j+d,d*=j;a=j;}

```

The 70-byte version stores `j` in `a`, which seems to have the same effect as returning `j`. If anyone knows, please tell me if that behavior is consistent and I'm allowed to use it.

Try It Online!

---

Here's a 127-byte version that overflows at a number of terms somewhere between 21 and 57:

```
long long n,d,i,j,k;s(a){for(n=i=1,d=j=2;a/i;n/d?n-=2*d/j:++i){n=n*++j+d,d*=j;for(k=1;k<99;)n%++k||d%k||(n/=k,d/=k);}return j;}

```

Try It Online!

It's pretty much the same as the first one, except the variables are long long integers rather than integers, and it includes `for(k=1;k<99;)n%++k||d%k||(n/=k,d/=k);`, which, for each number `k` from 1 to 98, divides `n` and `d` by `k` if they're both divisible by `k`.
> 1 votes

# Answer
# Haskell, ~~74~~ 73 bytes

```
p=2#1$0
(n#y)x=(n?y)(x*n)$(n+1)#(y*n)
(n?y)a f|a+y>y*n=f$a-y|1>0=n:f(a+y)

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence, rational-numbers
---


# Question
Title: Sample from the discrete triangular distribution
Given an integer `n >= 1` as input, output a sample from the discrete triangular distribution over the integers `k`, for `1 <= k <= n` (`1 <= k < n` is also acceptable), defined by `p(k) ∝ k`.

E.g. if `n = 3`, then `p(1) = 1/6`, `p(2) = 2/6`, and `p(3) = 3/6`.

Your code should take **constant expected time**, but you are allowed to ignore overflow, to treat floating point operations as exact, and to use a PRNG (pseudorandom number generator).

You can treat your random number generator and all standard operations as constant time.

This is code golf, so the shortest answer wins.

# Answer
> 4 votes
# Vyxal, ~~7~~ 6 bytes

*-1 thanks to @emanresu A*

```
›℅‹$℅x

```

Try it Online!

# Answer
> 6 votes
# JavaScript (ES7), 37 bytes

*-1 thanks to @Neil*

```
n=>(Math.random()*n*-~n+1|0)**.5+.5|0

```

Try it online!

### How?

We essentially pick a random integer in \\$\left\[1\dots\sum\_{k=1}^{n}k\right\]\\$ and then return the corresponding term in the sequence \\$1,2,2,3,3,3,4,4,4,4,\dots\\$ (this is A002024).

A more readable form of the formula is:

$$\left\lfloor\sqrt{2 \times\left\lfloor \operatorname{rand}()\times {n+1\choose 2}+1 \right\rfloor }+1/2\right\rfloor$$

leading to:

$$\left\lfloor\sqrt{2 \times\lfloor \operatorname{rand}()\times n\times(n+1)/2+1 \rfloor }+1/2\right\rfloor$$

where \\$\operatorname{rand}()\\$ is assumed to return a random value drawn from the uniform distribution in the interval \\$\[0,1\[\\$.

# Answer
> 5 votes
# Python, 57 bytes

```
lambda n:max(r(1,n),r(n))
from random import*
r=randrange

```

Attempt This Online!

### Python, 60 bytes

```
lambda n:max(divmod(randrange(n,n*n),n))
from random import*

```

Attempt This Online!

## Picture:

```
   |  0  1  2  3  4  5
---+------------------
1  |  1  1  2  3  4  5
2  |  2  2  2  3  4  5
3  |  3  3  3  3  4  5
4  |  4  4  4  4  4  5
5  |  5  5  5  5  5  5

```

# Answer
> 3 votes
# , 46 bytes

```
function(n)((1+4*runif(1)*n*(n+1))^.5-1)%/%2+1

```

Try it online!

`runif(1)` calculates a random number from the uniform distribution from zero to one. We then need to work-out which triangularly-increasing interval this lies in. So we multiply by the size of the full triangle (`n*(n+1)/2`) to get `c`, and solve the quadratic equation `x(x+1)/2=c` = `x^2+x-2*c=0` (using the quadratic formula) to get the answer `x`.

# Answer
> 3 votes
# Charcoal, 14 bytes

```
Ｉ⌊⁺·⁵₂⊕‽Ｘ⁺·⁵Ｎ²

```

Try it online! Link is to verbose version of code. Explanation:

```
            Ｎ   Input `n` as a number
         ⁺·⁵    Plus literal number `0.5`
        Ｘ    ²  Squared
       ‽        Random element of implicit range
      ⊕         Incremented
    ₂           Square root
  ⁺·⁵           Plus literal number `0.5`
 ⌊              Floor
Ｉ               Cast to string
                Implicitly print

```

Example: For `n=4`, the implicit range is `[0..20)`, which the remaining code maps `0..1` to `1`, `2..5` to `2`, `6..11` to `3` and `12..19` to `4`, thus `p(k)∝k` as desired.

# Answer
> 3 votes
# Python, 71 bytes

```
lambda x:x-abs((a:=r(x)-r(x+1))+(a>=0))
from random import*
r=randrange

```

Attempt This Online!

Surprisingly tricky. Uses the fact that the sum of 2 numbers form a rectangle, then using `a>=0` to add 1 to negative numbers then abs merges both halves of the triangle.

# Answer
> 1 votes
# C (gcc), 43 bytes

```
f(n){n=sqrt(2*(rand()/21e8*n*++n/2)+1)-.5;}

```

Try it online!

# Answer
> 1 votes
# Pyt, 9 bytes

```
Đř⇹0⇹Ř×ʀ↑

```

Try it online!

Port of @loopy walt's answer

# Answer
> 0 votes
# Raku, 24 bytes

```
{Bag(1..*Z=>1..$_).pick}

```

Try it online!

A `Bag` object is a set with multiplicity, and it has a `pick` method that returns a random key, where each key is weighted by its multiplicity in the bag. Here it's initialized with a list of the numbers from 1 up to the input argument `$_`, each one weighted by itself.

* `1 .. *` is the infinite list of natural numbers.
* `1 .. $_` is the list of natural numbers from 1 up to the input argument.
* `Z=>` zips those two lists together with the pair creation operator `=>`. It stops when it reaches the end of the shorter/noninfinite list, of course.

---
Tags: code-golf, random, restricted-complexity
---


title: Sum of Consecutive Squares

text:
# Question
Title: Sum of Consecutive Squares
### Your task

Given a integer input, \\$ n \\$ (such that \\$ n \> 1 \\$), decide whether it can be written as the sum of (at least 2) consecutive square numbers.

### Test cases

**Truthy:**

```
Input  Explanation
5      1 + 4
13     4 + 9
14     1 + 4 + 9
25     9 + 16
29     4 + 9 + 16
30     1 + 4 + 9 + 16
41     16 + 25
50     9 + 16 + 25

```

**Falsy:**

(Any number from 2 to 50 that's not in the truthy test cases)

### Clarifications and notes

# Answer
# Jelly, 5 bytes

```
Ẇḋ`ṫċ

```

Try it online!

```
Ẇḋ`ṫċ     – link, we call the argument n
Ẇ         – all contiguous sublists of [1, ..., n]
 ḋ        – dot product (vectorized) with...
  `       ... itself (` makes a monad from a dyad by repeating the argument)
   ṫ      – discard the first n-1 (for n>1, n^2 ≠ n, so it's ok)
    ċ     – count the occurences of n in this list

```
> 9 votes

# Answer
# , ~~57~~ ~~52~~ ~~49~~ 48 bytes

```
\(n)n%in%apply(array(1:n,1:0+n)^2,2,cumsum)[-1,]

```

Attempt This Online!

### Explanation outline:

1. Construct a matrix with `n+1` rows: filling up columns with `1:n` (with recycling). For `n=5`:

```
1    2    3    4    5
2    3    4    5    1
3    4    5    1    2
4    5    1    2    3
5    1    2    3    4
1    2    3    4    5

```
2. Square values in the matrix.
3. Take cumulative sum of the columns. We don't care about the additional values in the bottom-right triangle of the matrix, as those are bigger than `n^2` (which is bigger than `n`).

```
 1    4    9   16   25
 5   13   25   41   26
14   29   50   42   30
30   54   51   46   39
55   55   55   55   55
56   59   64   71   80

```
4. Discard the first row, as it contains squares (not constructed as sums of squares).
5. Check if `n` is in the matrix.
> 7 votes

# Answer
# Vyxal, 7 bytes

```
ÞS~Ḣ²Ṡc

```

Try it Online!

**How it works**

```
ÞS~Ḣ²Ṡc
ÞS       Sublists of range 1-n
  ~Ḣ     Keep lists with length >= 2
    ²Ṡ   Square and sum each sublist
      c  Does it contain n?

```
> 6 votes

# Answer
# Jelly,  ~~7~~  6 bytes

-1 thanks to Unrelated String (square after getting sublists of `[1..n]` avoiding ).

```
Ẇ²ḊƇ§ċ

```

A monadic Link that accepts an integer and yields the count of ways it is partitionable into consecutive (positive) squares (`0` is falsey while non-zero integers are truthy).

**Try it online!** Or see the test-suite.

### How?

```
Ẇ²ḊƇ§ċ - Link: integer, n
Ẇ      - all contiguous sublists of [1..n]
 ²     - square (vectorises)
   Ƈ   - filter keep those for which:
  Ḋ    -   dequeue (i.e. remove the singleton lists)
    §  - sums
     ċ - count occurrence of (n)

```
> 6 votes

# Answer
# JavaScript (Node.js), 58 bytes

```
n=>(g=i=>(s+=++i*i)-n?s>n?q<n&&g(++q,s=q*q):g(i):1)(s=q=1)

```

Try it online!

By definition
> 4 votes

# Answer
# JavaScript (ES6), 50 bytes

Returns \\$0\\$ or \\$1\\$.

```
f=(n,p=0,q)=>n?++p<n&&f(n-p*p,p,q?1:f)|!q*f(n,p):q

```

Try it online!

### Commented

```
f = (          // f is a recursive function taking:
  n,           //   n = input
  p = 0,       //   p = counter used to generate squares
  q            //   q = flag telling that we've started to subtract
               //       squares from n, initially undefined, then
) =>           //       set to f, then set to 1
n ?            // if n is not 0:
  ++p < n      //   increment p and abort if it's greater than
  &&           //   or equal to n
  f(           //   otherwise, do a 1st recursive call:
    n - p * p, //     subtract p² from n
    p,         //     pass p unchanged
    q ? 1 : f  //     set q to 1 if it's already defined or
               //     to f (truthy but NaN'ish) otherwise
  ) |          //   end of recursive call
  !q *         //   if q is defined, ignore the result of ...
  f(n, p)      //   ... the 2nd recursive call where n and p are
               //   left unchanged and q is undefined
:              // else:
  q            //   return q, which is coerced to 1 by the bitwise
               //   OR if and only if it's equal to 1, meaning
               //   that n is the sum of at least 2 squares

```
> 4 votes

# Answer
# K (ngn/k), ~~22~~ 21 bytes

```
{|//x=1_+\|+':3+\/=x}

```

Try it online!

**Comments**:

```
                 =x   / Generate identity matrix of size x
             3+\/     / Three times cumulative sum;
                      / This puts triangular numbers on the columns, starting with 1 at the diagonal
          +':         / Sum adjacent values; This gives square numbers
         |            / Reverse the matrix
       +\             / Cumulative sums; Now matrix has all sums of ranges of sqaures
     1_               / Remove first row; This correspond to the sums of a single square
|//x=                 / Is any of the values equal to x?

```

Try it with output of intermediate values.
> 4 votes

# Answer
# Japt, 8 bytes

```
§õ²ãx aU

```

Try it

```
§õ²ãx aU     :Implicit input of integer U
§            :Less than or equal to
 õ           :  Range [1,U]
  ²          :  Square each
   ã         :  Sub arrays
    x        :  Reduced by addition
      aU     :  Last 0-based index of U

```
> 4 votes

# Answer
# Python, 71 bytes

```
lambda n,k=0:(z:={k:=k+j*j for j in range(n)if j*j<n})&{l+n for l in z}

```

Attempt This Online!

# Python NumPy, 68 bytes

```
lambda n:{*(z:=cumsum(x:=r_[:n]**2)[x<n])}&{*z+n}
from numpy import*

```

Attempt This Online!

Returns the empty set for False and a nonempty set for True.

### How?

Compares (i.e. intersects) the sets {0,1,1+4,1+4+9,...,1+4+...+j^2} and {n,n+1,n+1+4,n+1+4+9,...,n+1+4+...+j^2} where j is the largest number such that j^2\<n.
> 4 votes

# Answer
# Python, 73 bytes

```
lambda n:n in[-~(r:=i//n+1)*(r*(r/3+i%n+1/6)+i%n*i%n)for i in range(n*n)]

```

Attempt This Online!

Formula for \\$\sum\_{i=x}^{x+r}i^2\\$ found using Wolfram Alpha, then golfed as hard as I could.
> 4 votes

# Answer
# Factor \+ `grouping.extras`, ~~60~~ 58 bytes

```
[ dup [1,b] 2 v^n tail-clump [ cum-sum rest ] gather in? ]

```

Try it online!

```
dup             ! duplicate input
[1,b]           ! range from 1 to input inclusive
2 v^n           ! square each
tail-clump      ! suffixes
[               ! begin gather
    cum-sum     ! cumulative sum
    rest        ! sans the first element
] gather        ! map, flatten, and uniqueify
in?             ! is the input we duped at the beginning in the sequence?

```
> 4 votes

# Answer
# Python, 55 bytes

```
f=lambda n,z=0,j=0:j*j<n and f(n,z<<j*j|1,j+1)or z&z>>n

```

Try it online!

Outputs 0 for falsey, nonzero for truthy.

Based on loopy walt's method of making a set of the cumulative sums of squares, then intersecting it with a copy that's shifted by `n`. This answer represents the set as a bit field stored as a positive number, which lets us shift it with `>>` and intersect with bitwise `&`.

**53 bytes**

```
f=lambda n,z=0,j=0:z&z>>n|(j*j<n>0<f(n,z<<j*j|1,j+1))

```

Try it online!
> 4 votes

# Answer
# , 19 bytes

```
e.[:,@(>:+/\*:)1+i.

```

Try it online!

Brute force: tries every possible infix of all the squares up to n.
> 3 votes

# Answer
# Python, 111 102 95 90 87 bytes

This uses `p` (positive) and `a` (antipositive?) to track the the beginning and end of a series of consecutive squares, only storing the sum (`s`) of squares between them.

If the sum is less then `n`, the square of `p` is added to the sum and `p` is incremented.

If the sum is greater than `n`, the square of `a` is subtracted from the sum and `a` is incremented.

When `p` is greater than `n`, the number has failed the test.

`p-a` is checked to see that at least 2 squares are included in the sum.

102 thanks to l4m2

90 thanks to gsitcia

```
f=lambda n,s=0,p=1,a=1:s!=n>p and f(n,s+[-a*a,p*p][x:=s<n],p+x,a+(x<1))or(s==n)&(p-a>1)

```

Attempt This Online!
> 3 votes

# Answer
# Charcoal, 15 bytes

```
Ｎθ⊙θ⊙ι⁼θΣＸ…·λι²

```

Attempt This Online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if `n` can be written as a sum of at least `2` consecutive squares, nothing if not. Explanation:

```
Ｎθ              Input `n` as a number
   θ            Input `n`
  ⊙             Any of implicit range satisfies
     ι          Current value
    ⊙           Any of implicit range satisfies
          …·    Inclusive range from
            λ   Inner value to
             ι  Outer value
         Ｘ      Raised to power
              ² Literal integer `2`
        Σ       Take the sum
      ⁼         Equals
       θ        Input `n`
                Implicitly print

```

Although the program includes  the only relevant sum is `0²+1²` but when the input is `1` the outer loop only goes up to `0` so that sum is never constructed.
> 3 votes

# Answer
# , 41 bytes

```
\(n)n%in%diffinv(array(1:n,1:0+n)^2)[-2,]

```

Attempt This Online!

This is mostly a golf of pajonk's answer that uses `diffinv(X)` rather than `apply(X,2,cumsum)` to calculate the cumulative sums.

### Changes from pajonk's answer:

3. Take the discrete integral of the columns. We don't care about the additional values in the bottom-right triangle of the matrix, as those are bigger than `n^2` (which is bigger than `n`), nor do we care about the additional row of zeros at the beginning (since they are smaller than `n`).

```
 0    0    0    0    0
 1    4    9   16   25
 5   13   25   41   26
14   29   50   42   30
30   54   51   46   39
55   55   55   55   55
56   59   64   71   80

```
4. Discard the second row, as it contains squares (not constructed as sums of squares).
> 3 votes

# Answer
# Haskell, 51 bytes

```
f x=elem x[sum$map(^2)[z..w]|z<-[1..x],w<-[z+1..x]]

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 44 bytes

```
!FreeQ[Tr/@Subsequences[Range@#^2,{2,#}],#]&

```

function that returns true-false

Try it online!
> 2 votes

# Answer
# Desmos, <sup>~~76~~ ~~60~~</sup> 58 bytes

```
l=[1...n]
f(n)=[0^{([a...a+b]^2.total-n)^2}fora=l,b=l].max

```

Try it on Desmos!

Outputs 0 or 1.
> 2 votes

# Answer
# Retina 0.8.2, ~~48~~ 38 bytes

```
.+
$*
((^1|11\2)+)(?<1>\1(?<2>11\2))+$

```

Try it online! Link includes test cases. Explanation: Vaguely based on my Retina 0.8.2 answer to Sum of two squares.

```
.+
$*

```

Convert to unary.

```
((^1|11\2)+)

```

Match a square number.

```
(?<1>\1(?<2>11\2))+

```

Match at least one additional consecutive square number; "named" capturing groups are used to reuse the captures from the previous square number.

```
$

```

Check whether the squares are able to sum to the input.
> 2 votes

# Answer
# Desmos, 54 bytes

```
f(N)=∑_{n=1}^N∑_{k=1}^N0^{(N-∑_{a=n}^{n+k}aa)^2}

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# Java 8, 84 bytes

```
n->{int i,j,c,r=c=i=0;for(;i<n;c=i*i)for(j=++i;j<n;r+=c==n?1:0)c+=j*j++;return r>0;}

```

Try it online!

---

For the science : inline solution using only Streams :

```
n->java.util.stream.IntStream.range(1,n).anyMatch(i->java.util.stream.IntStream.range(i+1,n).anyMatch(j->n==java.util.stream.IntStream.range(i,j+1).reduce(0,(a,b)->a+b*b)))

```
> 2 votes

# Answer
# Brachylog, 8 bytes

```
⟦sṀ^₂ᵐ+?

```

Try it online!

Tried a more declarative approach instead of this one but the constraint solver is not strong enough for anti-sums, it falls into infinite loops for falsy cases.

### Explanation

```
⟦          Range [0, …, N]
 sṀ        Sublist of Ṁany (i.e. at least 2) consecutive elements
   ^₂ᵐ     Map square
      +?   The sum is N

```
> 2 votes

# Answer
# SWI-Prolog, 64 bytes

```
\X:-X/_. X/Y:-between(2,X,Y),Z is Y-1,W is X-Y*Y,(W is Z*Z;W/Z).

```
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
LnIKŒOIå

```

Try it online or verify all test cases.

Minor alternative:

```
<tLnŒOIå

```

Try it online or verify all test cases.

More original, but longer (and slower) program (**9 bytes**):

```
Åœ¨t€¥PΘà

```

Try it online or verify all test cases.

**Explanation:**

```
L         # Push a list in the range [1, (implicit) input]
 n        # Square each inner integer
  IK      # Remove the input-integer from the list
    Œ     # Get all sublists
     O    # Sum each sublist
      Iå  # Check if the input-integer is in this list of sums
          # (after which the result is output implicitly)

<         # Decrease the (implicit) input-integer by 1
 t        # Pop and take the square root of this input-1
  L       # Pop and push a list in the range [1, floor(sqrt(input-1))]
   n      # Square each inner integer
    ŒOIå  # Same as above

Åœ        # Get all lists of positive integers that sum to the (implicit) input
  ¨       # Remove the last [...,[input]] sub-list
   t      # Get the square root of each inner integer
    €     # Map over each inner list of decimals:
     ¥    #  Pop and push its deltas / forward-differences
      P   # Get the product of each inner list of forward-differences
       Θ  # Check for each product if it's equal to 1 (with a 05AB1E-truthify)
        à # Check if any is truthy
          # (after which the result is output implicitly)

```
> 1 votes

# Answer
# C (gcc), 82 bytes

```
i;j;s;t;f(n){for(s=i=0;s-n&&++i<n;)for(s=i*i,t=j=i;!t*s-n&&++j<n;t=0)s+=j*j;s-=n;}

```

Try it online!

Inputs \\$n\\$.
Returns a falsey value if \\$n\\$ is the sum of consecutive squares or a truthy value otherwise.
> 1 votes

# Answer
# ///, 39 bytes

```
/13///14///25///29///30///41///50///5//

```

Try it online!

*Sigh.*

I thought there was some light at the end of the tunnel with this idea, but it turns out the simple greedy approach fails for a few of the inputs. Plus, hardcoding it is a third of the length.
> 1 votes

---
Tags: code-golf, math, number, decision-problem, integer
---


title: Calculate the overlapping line

text:
# Question
Title: Calculate the overlapping line
`(l, r)` defines a line whose left end is at `l` and the right end is at `r`, on a 1-dimensional space.

Given 2 lines `b = (0, bz)` and `f = (i, i + fz)`, `v = (l, r)` is the overlapping part of these lines. When `b` and `f` do not overlap (when `v` cannot have a positive length), `v = (0, 0)`.

```
(input)   -> (output)
bz, fz, i -> l, r

```

The data type (`int`, `float`, `string`, etc.) for each value should be able to represent all *integers* from `-128` to `127`, inclusive.

You can change the order of input and output variables.

### Examples

```
0, 0, 0 -> 0, 0
1, 1, 1 -> 0, 0
1, 2, 3 -> 0, 0
1, 2, -3 -> 0, 0
2, 1, 1 -> 1, 2
4, 2, 1 -> 1, 3
2, 2, -1 -> 0, 1
2, 4, -1 -> 0, 2

```

# Answer
# Python 3.8 (pre-release), 44 bytes

```
lambda a,b,c:[c*(a>c>0),min(a,b+c)*(a>c>-b)]

```

Try it online!

Test harness borrowed from @ophact.

The condition for overlap to exist is that both right ends are right of both left ends. Two of those four pairwise inequalities are as I understand it satisfied automatically (up to equality, but that does no harm), the other two can be folded into a single chained comparison `a>c>-b`. This is used to zero out the result we computed under the assumption that overlap exists. The left end makes a further shortcut using that `b` is guaranteed to be nonnegative and that one of the two possible ends is `0`.
> 2 votes

# Answer
# Python 3.8 (pre-release), 52 bytes

```
lambda a,b,c:[d:=c*(c>0),e:=min(a,c+b)]*(d<e)or[0,0]

```

Try it online!

## Explanation

The overlapping line starts from the beginning of the second line (measured by starting point) because it cannot start from the beginning of the first line (unless both lines start at the same point) because then the beginning would not be part of the second line, and it cannot start at the end of any line because it would leave the line directly afterward.

It ends at the first endpoint, where it first "leaves" a line.

If the start is not less than the end (as found according to the above), then the lines do not overlap, and we can then return `[0, 0]`.
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
Ý+IÝÃÁ2£DËi00S

```

I/O: three loose inputs in the order \\$fz,i,bz\\$; output as pair \[\\$r,l\\$\].

Try it online or verify all test cases.

**Explanation:**

Step 1: Calculate `[r,l]` for overlapping test cases:

```
Ý        # Push a list in the range [0, first (implicit) input fz]
 +       # Add the second (implicit) input `i` to each to make the range [i,fz+i]
  I      # Push the third input `bz`
   Ý     # Pop and push a list in the range [0,bz]
    Ã    # Keep all values in [i,fz+i] that are also in [0,bz]
     Á   # Rotate this list once towards the right
      2£ # Keep (up to) the first two values
         # (this is the output [r,l] for the overlapping test cases)

```

Step 2: Deal with the edge cases of `[]` (no overlap) or `[x]` (\\$i=bz\\$ or \\$fz+i=0\\$):

```
D        # Duplicate the list
 Ëi      # If both values are the same (truthy for [] and [x], falsey for [r,l]):
   00S   #  Push [0,0] instead
         # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Charcoal, 27 bytes

```
Ｎθ≔Φ⁺…⁰ＮＮ⁼ι﹪ιθηＩ⟦∨⌊η⁰⊕∨⌈η±¹

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ

```

Input `bz`.

```
≔Φ⁺…⁰ＮＮ⁼ι﹪ιθη

```

Input `fz` and `i`, create the range `[i,i+fz)`, and filter out values not in the range `[0,bz)`.

```
Ｉ⟦∨⌊η⁰⊕∨⌈η±¹

```

If there are no values left then output `0,0` otherwise output the endpoints of the remaining values.
> 1 votes

# Answer
# Jelly, 12 bytes

```
Ż+⁵fŻ}0ṚE?.ị

```

A full program that accepts `fz bz i` and prints the line as `[l, r]`.

**Try it online!**

### How?

```
Ż+⁵fŻ}0ṚE?.ị - Main Link: fz, bz
Ż            - zero range fz -> [0,1,2,...,fz] (call this F)
  ⁵          - 3rd argument, i
 +           - add           -> [i,i+1,...,i+fz]
     }       - use right argument, bz:
    Ż        -   zero range  -> [0,1,2,...,bz] (call this B)
   f         - F filter keep if in B
         ?   - if...
        E    - ...condition: all equal? (i.e. is that a single point)
      0      - ...then: yield zero
       Ṛ     - ...else: reverse
          .  - 0.5
           ị - index into -> [last value, first value] (when given 0 this is [0,0])
             - implicit print

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
(IntervalIntersection@@Interval/@{{0,#1},{#3,#3+#2}})[[1]]&

```

Try it online!
> 0 votes

---
Tags: code-golf, geometry
---


title: Factorial in haiku!

text:
# Question
Title: Factorial in haiku!
## Task

Create a program that calculates the factorial of a number using no built-in factorial functions. Easy? The catch is that you must write your entire program (including testing it) in haiku form.

You can use as many haikus as you need, but when pronounced, they must follow the 5-7-5 syllable format.

### Scoring

This is a , so you must get the most upvotes to win. Your program must consist of at least one full haiku, and all haikus must be complete.

When reading code, the first line of each haiku will have 5 syllables, the second will have 7, and the third will have 5.

# Answer
> 57 votes
# Smalltalk

(evaluate in a workspace; opens a dialog, asks for a number and prints the result on stdout):

```
"in" "this" 'poem,' "you" "must"
"pronounce" "characters" "like" "these:"
"return(^)," "and" "times(*);" "please".

"but" 'never' "in" "here"
"tell" "anyone" "about" "those"
"few" "parentheses".

"otherwise" "these" "words"
"are" "stupid" "and" "this" "coded"
"rhyme" "is" "wasted" Time.

"let" "us" "now" "begin"
"by" "defining," "in" Object
"and" compile: "the" "rhyme:"

'fac: "with" arg"ument"
"to" "compare" arg <"against" 2 ">"
"and" ifTrue: [ ^"return"

"["1] "or" ifFalse: "then"
["return"^ arg *"times" "the" "result"
"of" ("my"self ")getting"

"the" fac:"torial"
"of" "the" "number" arg "minus"-
1 "[(yes," "its" "easy")]'.

("Let" "me" "my"self "ask"
"for" "a" "number," "to" "compute"
"the" fac:"torial"

("by" "opening" "a"
"nice" Dialog "which" "sends" "a"
request: "asking" "for"

'the Number to use'
"(which" "is" "(" "treated" ) asNumber)
"then" print "the" "result".

```

I tried to bring in some reflection ("in this poem") and kigo as well. Also, some western style rhyme elements are included (please-\>these, time-\>rhyme); however, being neither native speaker of Japanese, nor of English, forgive any stylistic details ;-)

# Answer
> 41 votes
# Java - 2 haikus

```
protected static
        int factorial(int n) {
    if (n == 0) {
        return n + 1;
    } return factorial(n
            - 1) * n;}

```

Even when the question isn't , I often catch myself golfing the answer. In this case, I golfed the number of haikus.

I pronounce it so:

> protected static
> int factorial int n
> if n is zero
>
> return n plus one
> return factorial n
> minus one times n

---

Test program:

```
class Factorial {                                    // class Factorial
    public static void main(String[]                 // public static void main string
            command_line_run_args) {                 // command line run args

        int i = 0;                                   // int i is zero
        while (7 != 0)                               // while seven is not zero
            System.out.                              // System dot out dot

                    println(i + "!"                  // print line i plus not
                            + " = " + factorial(     // plus is plus factorial
                            i += 1));}               // i plus equals 1

    protected static
            int factorial(int n) {
        if (n == 0) {
            return n + 1;
        } return factorial(n
                - 1) * n;}}

```

Note that this program starts outputting `0`s fast; that is a result of overflow. You could easily get larger correct numbers by changing each `int` to `long`.

Standard pronunciations for `System.out.println` and `public static void main(String[] args)` are reflected in the program.

# Answer
> 41 votes
## Haskell

```
fact :: Int -> Int          -- fact is Int to Int
fact x = product (range x)  -- fact x is product range x
range x = [1..x]            -- range x is 1 [pause] x

```

Haskell education time:

* The `range x` function creates a list of integers from 1 up to the value of `x`.
* The `fact x` function multiplies all the values of the list `range x` together to compute the result.
* The first line says that the `fact` function takes an integer and returns an integer.

# Answer
> 28 votes
# APL

```
factorial←{×/⍳⍵}

```

> Factorial is—
> the product of naturals
> up to omega

# Answer
> 21 votes
# Shakespeare

```
The Products of Love:
A haiku tragedy with
mathy undertones.

Romeo, a man.
Juliet, a maiden fair.
Friar John, a monk.

Act I: A Cycle.
Scene I: Pertinent Values.
[Enter Romeo]

[Enter Friar John]
Romeo: Listen to thy
heart. Thou art thyself.

Friar John: Thou art
as forthright as a songbird.
[Exit Friar John]

[Enter Juliet]
Romeo: Thou art as fair
as a violet.

Scene II: Questioning
Themselves. [Exit Juliet]
[Enter Friar John]

Friar John: Art thou
as just as the sum of me
and a nobleman?

Romeo: If so,
let us proceed to scene III.
[Exit Friar John]

[Enter Juliet]
Romeo: Thou art as good
as the product of

thyself and myself.
Juliet: Thou art as fierce
as the sum of an

eagle and thyself.
We must return to scene II.
Scene III: A Lengthy

Title for a Brief
Dénouement; Or, The Last Word.
[Exit Friar John]

[Enter Juliet]
Romeo: Open your heart.
[Exit Romeo]

```

An (imagined) test case:

Despite its length, this program just takes a single integer as input and provides a single integer as output. So:

```
6 ↵ 720
7 ↵ 5040
0 ↵ 1    1 ↵ 1

```

("Six, seven-twenty. / Seven, five thousand forty. / Zero, one. One, one.")

# Answer
> 12 votes
# Python 2, 4 Haikus

A complete Python 2 program `haifac.py`. Run as `python haifac.py <n>`

```
#run this full program
import operator as\
op; import sys#tem

#please provide an arg
n = sys.argv[1]
def haifac (n):

    if n < 1:
        return 1#to me at once
    else:#do something else

        return op.mul(
            n, haifac(n - 1))
print haifac(int(n))

```

Pronounciation:

> run this full program
> import operator as
> op import system
>
> please provide an arg
> n equals sys arg v 1
> define hai fac n
>
> if n less than 1
> return 1 to me at once
> else do something else
>
> return op dot mul
> n hai fac n minus 1
> print hai fac int n

# Answer
> 9 votes
## GolfScript, 2 Haikus

```
),{0>},{,,*}*

```

Read as haiku, enumerating each keystroke:

```
#close parenthesis
#comma open-brace zero
#greater-than close-brace

#comma open-brace
#comma comma asterisk
#close-brace asterisk

```

With test case (5 haikus):

```
[1 2 3]4+          #generate the array [1 2 3 4]
{                  #start creating block
),{0>},{,,*}*      #actual factorial code
}%                 #close block and map across array (so that we should have [1! 2! 3! 4!])
[1 2 6]2.3**12++=  #generate the array [1 2 6 24] and check for equality

```

Read as haiku:

```
#open-bracket one
#space two space three close-bracket
#four plus open-brace

#close parenthesis
#comma open-brace zero
#greater-than close-brace

#comma open-brace
#comma comma asterisk
#close-brace asterisk

#close-brace percent-sign
#open-bracket one space two
#space six close-bracket

#two period three
#asterisk asterisk one
#two plus plus equals

```

# Answer
> 9 votes
# Whitespace

This makes uses of one of the most famous *haiku*s, and a great deal has been written about it.

No idea why nobody has done this before, it doesn't even take any effort!

First of all, before reading the poem, I want you to lean back, relax, and enjoy the tranquility created by the great void surrounding the poem. It emphasizes the pond, surrounded by a vast landscape.

```
古池や
蛙飛びこむ
水の音

```

source code on filebin

In case you do not speak Japanese, this is pronounced as follows:

> fu ru i ke ya
>
> ka wa zu to bi ko mu
>
> mi zu no o to

Naturally, it is counted by morae. The *kireji* is や (*ya*), the *kigo* (seasonal reference) is 蛙 (*kawazu*, frog, -\> spring).

Using the linux interpreter from the official page, you can use it like this:

> $ echo 5 | ./wspace .ws

# Answer
> 8 votes
# PHP, 4 haikus

*All-in-rhyme* haikus!

```
function haiku($can) { // function haiku can (5)
    if ($can == 1) // if can is equal to one (7)
        return ++$stun; // return increase stun (5)

    if ($can == 0) { // if can equals ou (5)
        echo "It is one, you know! "; //echo "It is one, you know! " (7)
        return 1+$blow; } //return one plus blow (5)

    if ($can > $fun) { //if can exceeds fun (5)
        return haiku($can-1) //return haiku can less one (7)
            *$can; }} //multiplied by can (5)

if (null == $knee) { // if null equals knee (5)
    $free=0+3; // free equals zero plus three (7)
    echo haiku($free); } // echo haiku free (5)

```

# Answer
> 8 votes
# Forth

```
: fugu 1              \ colon fugu one                = 5
swap 1 + 1 ?do        \ swap one plus one question do = 7
i * loop ;            \ eye star loop semi            = 5

```

*Fugu* is the function and my attempt at *kigo*: blowfish is a winter reference. I intend `?do` to be *kireji*, the turning point, before the counted loop.

# Answer
> 6 votes
# Mathematica

```
f[x_]:=     (* f of x defined *)
 x f[x-1]   (* x times f of x less 1 *)
f[1]=1      (* Mogami River *)

```

Pedants may read the last line as "f of 1 is 1", but I couldn't resist the shout-out to Basho.

### Testing:

```
Table[f[n],     (* Table f of n *)
 {n, 1, 10, 1}] (* n from 1 to 10 by 1 *)
ListLogPlot[%]  (* ListLogPlot output *)

```

### Returning:

```
(1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800)

```

### Linguistic Distinctiveness Bonus Haiku (inspired by @cormullion)

```
Rewrite any term
High-level functions abound —
Mathematica

```

# Answer
> 5 votes
## Batch

```
@set /a t=1 &^
for /L %%a in (2, 1, %1) ^
do @set /a t*=%%a

```

**Pronunciation**; ignores mathematical expressions as well as these symbols `@ / % ^ , ( )`:

> set a t 1 and
> for L a in 2 1 1
> do set a t a

Note; this calculates the factorial, it doesn't output it - the variable `t` contains the factorial.

The following Haiku / code can be appended to the same batch file to output the factorial (the `|`'s are pronounced as pipe):

```
@echo %t% ||^
When will you learn, unclemeat ^
Why must you use Batch?

```

# Answer
> 5 votes
# Clojure

```
(->> *command-line-args*                ; thrush com-mand line args
  seq last read-string range (map inc)  ; seq last read string range map inc
  (reduce *) println)                   ; re-duce times print-lin

```

# Answer
> 5 votes
### newLISP

The parentheses are not pronounced:

```
(define (fac n (so))            ; define fac n so
(if (= n 0) 1                   ; if equals n zero 1
(* n (fac (dec n)))))           ; times n fac dec n

(for (n 0 10)                   ; for n zero ten
; let's test from zero to ten
(println (fac n thus)))         ; printline fac n thus

```

> Lisp code consists of
>
> numerous parentheses
>
> and a few functions

# Answer
> 5 votes
# F#

```
let fact n =
    [1..n] |>
    Seq.fold (*) 1

```

> let fact of n be
> from one up to n, apply
> Seq dot fold star one

# Answer
> 5 votes
# LiveScript

This one's medieval:

```
prelude = ^^ do                       # prelude is clone do
  require \prelude-ls                 # require prelude dash ls
{ product } = prelude                 # product is prelude

story = (ah) ->                       # story is ah such:
  ones-misery = (one) ->              # one's misery is one such
    let death = product               # let death be product

      fight = [1 to one]              # fight is one to one
      why = (one) -> death <| fight   # why is one such death take fight
  ones-misery ah                      # one's misery ah

room = console.log                    # room is console log
room <| (story 10)!                   # room take story three bang
[null of { use : this }]              # no of use is this

```

Prints `3628800`, which is `10!`. It's a little roundabout: The function `story` returns a function `ones-misery`, which always returns the answer. It's artsier that way.

No filler comments or unnecessary strings!

---

Bonus debugging story:

> I burst out laughing
> when informed that a bug was
> "`death` is `undefined`"

# Answer
> 5 votes
## Haskell

This one will be a **rhyming** haiku!

```
fact 0=1                     --fact zero is one
fact ton=ton * (fact stun)   --fact ton is ton times fact stun
        where stun=pred ton  --where stun is pred ton

```

Yeah!

Note: Pred means the previous number. Also in haskell, you can have multiple definitions of a function, and the first one that makes sense is used.

# Answer
> 4 votes
**Ruby - One Haiku**

```
ARGV.first.to_i.
 tap do |please| puts 1.upto(
 please ).inject( :*) end

```

Read (ignoring punctuation, but including one emoticon) like this:

```
 arg vee first to i
   tap do please puts one up to
 please inject smile end

```

# Answer
> 4 votes
In SML:

```
fun fact 0 = 1
  | fact n = n*fact(n-1)
  ;

```

read as:

```
"fun fact 0 is one,
bar that, fact n is n times
fact of n less one"

```

# Answer
> 4 votes
# Perl

```
$r = 1; for(1           # r gets one for one
.. pop @ARGV) { $r *=   # to pop arg v r splat gets
$_; } print $r;         # the default print r

```

Toss this into a file named `f.pl`

And the output:

```
$ perl f.pl 3
6$ perl f.pl 1-1
1$ perl f.pl 10
3628800$

```

Which is read as:

```
perl f p l three
perl f p l one less one
perl f p l ten

```

# Answer
> 3 votes
## Perl

I know it's against the rules to use ready-made functions, but here's what I get.

Imagine your task is to instruct an over-sized rodent:

```
use Math::BigRat; use
feature 'say'; use warnings; say
new Math::BigRat($_)->bfac

```

I can only guess what the last word means and how it's pronounced, but I assure you it is one syllable. Apparently he doesn't understand what you want from him, so you have to elaborate (easing on quality standards as you loose patience):

```
use Math::BaseConvert
':all'; no strict subs; no warnings;
reset and say fact($_)

```

still to no avail. Then you have to explain it in plain English:

```
no strict; no warnings;
use Math::Combinatorics;
say factorial($_)

```

What happened next I don't know, but code is valid:

```
perl -nE 'use Math::BigRat; use feature "say"; use warnings; say new Math::BigRat($_)->bfac'
42
1405006117752879898543142606244511569936384000000000

```

and

```
perl -nE 'use Math::BaseConvert ":all"; no strict subs; no warnings; reset and say fact($_)'
33
8683317618811886495518194401280000000

```

and

```
perl -nE 'no strict; no warnings; use Math::Combinatorics; say factorial($_)'
16
20922789888000

```

# Answer
> 2 votes
### Python

```
lambda n: reduce(
    lambda a, b: a * b,
    range(1, n), n)

```

The way I read it:

> ```
> lambda n: reduce
> lambda a b: a times b
> range 1 to n, n
>
> ```

\`

# Answer
> 2 votes
**C**

```
#include <std\
io.h>
#include \
<stdlib.h>

int main(int argc
 , char** argv)
{   // iteratively
    // compute factorial here
long int n = \
0, i \
= 0, r = \
1 /*
product starts at one*/;

if (argc
> 1) { n =
strtol(argv[\
1], NULL, 10)
; if (n
< 0) {
       printf("Arg must\
       be >= 0\n");
       exit(-
    1);}
} i =
n;
while (i) { r
= r * i;
    i
--;
} /* print
the result*/ printf(
"%d factorial\
equals %d\
\n", n
, r);
/*done*/}

```

**Pronounciation:**

pound include standard
I/O dot h pound include
standard lib dot h

int main int arg c
comma char star star arg v
open brace comment

iteratively
compute factorial here
long int n equals

zero comma i
equals zero comma r
equals one comment

product starts at one
semicolon if arg c
is greater than one

open brace n is
str-to-l of arg v sub
one comma NULL comma ten

semicolon if
n less than zero begin
printf arg must

be greater than or
equal to zero backslash
n semicolon

exit negative
one semicolon end brace
end brace i equals

n semicolon
while i open brace r
equals r times i

semicolon i
decrement semicolon
close brace comment print

the result printf
percent d factorial
equals percent d

whack n comma n
comma r semicolon
comment done end brace

# Answer
> 2 votes
# Python

Uses a single haiku to do the job!

```
f = lambda x:   \ #  f is lambda x:
    0**x or x * \ #    zero pow x, or x times
    f(x-1)        #    f(x minus 1)

```

This defines a recursive lambda which calculates the factorial - `0**x` handles the case of 0 as it evaluates to `1`.

# Answer
> 1 votes
Are we allowed to use filler?

Python 2 haikus:

```
number = num + 1
a = 13 + 4
b = 14

nuum = len([1])
for i in range(1, number):
    nuum *= i

```

# Answer
> 1 votes
## C# - 3 haikus

I removed the usual C# using, namespace and class definition clutter, which would be a 4th haiku.

```
public static void
Main(){int num = Convert.
ToInt32

(Console.ReadLine());
 Console.WriteLine(num ==
 0 ? 1 :

Enumerable.
Range(1, num).Aggregate
((i, j) => i * j));}

```

which I read as

```
public static void
Main int num equals Convert
To int thirty-two

Console dot Read line
Console Write line num equals
zero? then one, else

Enumerable
Range 1 to num aggregate
i j i times j

```

# Answer
> 1 votes
## Haskell

```
module Haiku where          -- read literally.
fac x = let in do           -- = is read as 'equals'
product [1..x]              -- product one to x

```

note that the module .. where is added automatically to any Haskell code without it at compilation, so not writing it is practically cheating.

# Answer
> 1 votes
**C**

Least beautiful haiku ever.

```
int main(int argc,
char *argv[]){int in,out;
sscanf(argv

[1],"%d",
&in);out=1;while
(in >

1){out*=
in--;}printf(
"%d",out);}//done

/*
Int main, int argc,
char star argv. Int in out.
Sscanf argv

sub one, percent d,
and in. Out equals one. While
in is greater than

one, out times equals
in minus minus. Printf
percent d out. Done
*/

```

# Answer
> 1 votes
**JAVA:**

In response to the question and to the Dwaiku (Double-Haiku or whatever you wanna call it) posted by Quincunx in Java, here's the correct Haiku:

```
public static int factorial(int n) {
   return (n==0) ? (n+1) : (factorial(n-1) * n);
}

```

# Answer
> 1 votes
### Javascript - Two Haikus

```
function factor (a) {          // function factor a
  if(!a){ return 1 ||          // if not a return 1 or
    a & 17}                    // a and seventeen

  else if (a + 1){             // else if a plus one
    return a * factor          // return a into factor
    (a + ( - 1) )  }}          // a plus minus one

```

I am not a native speaker. So, I used a dictionary to count the syllables. Hopefully, it's good enough. Any feedback is welcome :)

# Answer
> 1 votes
**Powershell, 2 Haikus**

```
function facto ($num){    # function facto num
$i = 1; 1..$num|          # i equals one; i to num
foreach { $i =            # for each i equals

$i * $_}; write $i}       # i times this write i
$answer = facto $args[    # answer equals facto args
0]; write $answer         # zero write answer

```

# Answer
> 1 votes
**Befunge-93**

Three haikus:

```
0&>:v
-:|:>1>
v#>$\
>:>>v
>$.@v<<
^#v*_
#>>>v
<<:\<>^
<#<#<

```

Last line is admittedly kind of cheaty.

Try here: http://www.bedroomlan.org/tools/befunge-93-playground

# Answer
> 1 votes
# Perl - 3 Haikus

This one useds some clever formatting and pronunciations - it also disregards symbols.

```
print "Enter number: ";
chomp(my $num = <STDIN>);
$result = 1;
for $x (1..$num) {
  $new = $x * $result;
  $result = $new;
}
if (1) { print "$result\n .
Is the factorial of\n";
if ($result) { print "$num"; }

```

Haiku:

> Print: En-ter num-ber
> Chomp: my num e-quals STD (stand)-IN
> Re-sult e-quals one
> For x one to num (or 'one range num')
> New e-quals x times re-sult
> re-sult e-quals new
> If one: print re-sult
> Is the fac-to-ri-al of
> If re-sult: print num

Let me know if I messed up anywhere.

# Answer
> 1 votes
# Mathematica - One Haiku (+1 extra (2 counting title))

```
factorial[n_]
 := Product @@
  Range[1, n]

```

> fac-tor-i-al en
>
> set de-layed pro-duct ap-ply
>
> range from one to en

From some simple words

Complex functions can arise

Mathematica

# Answer
> 1 votes
# C (GCC), 4 haikus

```

int fac(int number) { // int fac int number
        if (number == 0) { // if number equals zero
                puts("Done."); return 1; // puts done return one
        }

        else return number // else return number
                * fac(number - 1); // times fac number minus one
        puts("Unreachable"); // puts unreachable
}

main(argc, argv) // main arg-c arg-v
        char ** argv; { // char pointer pointer arg-v
        char c = getchar(); // char c is getchar

        printf("%" // print-f ampersand
                "d", fac(c - '0')); // d fac c minus zero
        return +0; // return plus zero
}

```

Try It Online!

# Answer
> 0 votes
## Python 2

```
print(reduce(lambda              # print reduce lambda
    a,b: a * b, range(1,         # a b a times b range one
        1 + input()), 1))        # one plus input, one

```

# Answer
> 0 votes
# Clojure

```
(defn fact [n] (if                  # def-fun fact n if
  (zero? n) 1                       # zero question mark n 1
  (* n (fact (dec n)))))            # times n fact dec n

```

# Answer
> 0 votes
# Python - Two Haikus

```
val = int(input())        -> val is int(input())
for hi in range(1,n):   -> for hi in range one to n
    val *= hi           -> val is val times hi

# Still a cool haiku    -> Just read it
print(n)                -> print val in parentheses
# Completed haiku       -> Just read it

```

Try it online!

---
Tags: math, popularity-contest, source-layout, factorial
---


title: Sum of numbers of arbitrary length

text:
# Question
Title: Sum of numbers of arbitrary length
Your function must accept 2 strings which are correct numbers. It needs to sum them up (without rounding and floating point errors) and return the result (which is also a correct number) without any leading zeros in the integer part, trailing zeros in the decimal part and without minus if the answer is 0 i.e. `-0` is not allowed.

A correct number is a string which can start with a leading minus, contains only digits and can contain only one dot which will be between the digits:

```
'1234567890'
'-1234567890'
'12345.67890'
'-12345.67890'

```

In other words, it matches the regex `-?\d+(\.\d+)?`

Your input will always be valid so you don't need to think about empty strings, etc.

The input strings can be as large as possible in your programming language, but it is guaranteed that the length of the resulting string will not be larger than what is available in your programming language.

### Some test cases:

```
'1', '1' --> '2'
'0', '0' --> '0'
'9', '1' --> '10'
'001.002', '3.400' --> '4.402'
'5', '-5.0' --> '0'
'2', '-2.5' --> '-0.5'
'12345', '67890' --> '80235'
'-50.6', '20.53' --> '-30.07'
'-001.00', '00100' --> '99'
'-00.100', '-0.20' --> '-0.3'
'0.1', '0.2' --> '0.3'
'1000000000000', '-0.000000000001' --> '999999999999.999999999999'

```

The shortest code in each programming language wins!

# Answer
> 8 votes
# Raku,  ~~17~~  15 bytes

```
$~*+*o**.FatRat

```

Try it online!

This converts both arguments to `FatRat`s (arbitrary sized bignums), before adding them together and stringifying the result. You could remove the `o**.FatRat` part, but this would use `Rat`s, which decay to floating point numbers once the precision needed is too high.

# Answer
> 7 votes
# Java 8, ~~103~~ 102 bytes

```
import java.math.*;a->b->new BigDecimal(a).add(new BigDecimal(b)).stripTrailingZeros().toPlainString()

```

Try it online.

**Explanation:**

```
import java.math.*;        // Required import for BigDecimal
a->b->                     // Method with String as two parameters & return-type
  new BigDecimal(a)        //  Convert the first input to a BigDecimal
   .add(                   //  Plus:
        new BigDecimal(b)) //   The second input as BigDecimal
  .stripTrailingZeros()    //  Remove any no-op trailing 0s
  .toPlainString()         //  Convert and return it as plain String (so no scientific
                           //  notation)

```

# Answer
> 6 votes
# Fig, \\$5\log\_{256}(96)\approx\\$ 4.116 bytes

```
B+_x_

```

Try it online!

Since Fig uses `BigDecimal`s, this doesn't suffer from floating point issues as some other answers do.

```
B+_x_
    _ # Convert first input to number
  _x  # Convert second input to number
 +    # Add
B     # Convert to string

```

# Answer
> 4 votes
# Python, 84 bytes

```
lambda*x:(s:=str(sum(map(Decimal,x))))[-2:]=='.0'and s[:-2]or s
from decimal import*

```

Attempt This Online!

Normal numbers succumb to floating point inaccuracies, so we need to convert to `decimal.Decimal`.

# Answer
> 3 votes
# Charcoal, ~~72~~ 69 bytes

```
≔Ｅ²Ｓθ≔Ｅθ∧№ι.⌕⮌ι.η≔ΣＩＥθ⁺⁻ι.×0⁻⌈η§ηκθ≔Ｘχ⌈ηη‹θ⁰Ｉ÷↔θη¿﹪θη«.Ｗ﹪↔θη«≧÷χηＩ÷ιη

```

Try it online! Link is to verbose version of code. Feels very long somehow. Explanation:

```
≔Ｅ²Ｓθ

```

Input the two strings.

```
≔Ｅθ∧№ι.⌕⮌ι.η

```

See how many digits each has after the decimal (if any).

```
≔ΣＩＥθ⁺⁻ι.×0⁻⌈η§ηκθ

```

Scale them both to be integers and take the sum.

```
≔Ｘχ⌈ηη‹θ⁰Ｉ÷↔θη

```

Calculate the effect of the scaling and output the integer part of the result.

```
¿﹪θη«.

```

If the result is not an integer then output a `.`.

```
Ｗ﹪↔θη«≧÷χηＩ÷ιη

```

Output successive digits until the remainder is zero.

40 bytes by importing Python's `decimal.Decimal`:

```
≔ＩΣＥ²▷⪫⟦d¦.Dω⟧ecimalＳθＷ›№θ.Σ§θ±¹≔…θ⊖Ｌθθθ

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
≔ＩΣＥ²▷⪫⟦d¦.Dω⟧ecimalＳθ

```

Input the two strings, convert them to `decimal.Decimal`, take the sum, then cast back to string again.

```
Ｗ›№θ.Σ§θ±¹

```

Repeat while the string contains a `.` and does not end in a digit `1-9`...

```
≔…θ⊖Ｌθθ

```

... remove the last character.

```
θ

```

Output the final string.

# Answer
> 3 votes
# bash, + bc, 30 bytes

```
bc<<<$1+$2|sed -r "s/\.*0+$//"

```

Try it online!

## How?

This takes advantage of `bc` being an arbitrary precision calculator language. It pipes the input (expected to be two arguments) to `bc` which adds them.

10 bytes to do the calculation, `bc<<<$1+$2`. 20 bytes to pipe to `sed` and remove trailing zeroes.

The golf-y bit is replacing `echo` with the bash here string (`<<<`), as in this tip. The code is the equivalent of `echo $1+$2 | bc`. This is my first attempt at a challenge in a language other than R. I would be interested in tips to golf further.

Try it online!

## Example output

I am not exactly sure how to provide a list of string test cases on TIO. In the absence of that, here is the example output for the final test case on my machine (script is called `calc.sh`):

```
$ ./calc.sh '1000000000000' '-0.000000000001'
999999999999.999999999999

```

```
$ ./calc.sh '-00.100' '-0.20'
-.3

```

## bash \+ bc, 31 bytes

This did not strip *all* trailing zeroes, as pointed out in the comments by @roblogic.

```
m=`bc<<<$1+$2`
echo ${m//[0$]/}

```

Try it online!

## Answer which did not meet spec, 10 bytes

```
bc<<<$1+$2

```

Unfortunately, as pointed out by
Ismael Miguel in the comments, the question says to

> return the result (which is also a correct number) without any leading zeros in the integer part, trailing zeros in the decimal part and without minus if the answer is 0

This did not remove all trailing zeroes.

# Answer
> 2 votes
# Excel, ~~7~~ 9 bytes

```
=A1+B1&""

```

# Answer
> 2 votes
# Japt, 1, 3 or 19 bytes

None of these can handle the last test case as the decimal exceeds JavaScript's native number support. Links include all other test cases, taking input as an array of 2 strings.

Outputs an integer, subject to floating point inaccuracies.

```
x

```

Try it

Outputs an string, subject to floating point inaccuracies.

```
x s

```

Try it

Outputs a string, with no floating point inaccuracies.

```
x x¡X°s q. hP ÌÊÃrÔ

```

Try it

# Answer
> 2 votes
# PARI/GP, 163 bytes

```
g(s)=eval(strjoin(t=strsplit(s,".")))/10^if(#t>1,#t[2])
h(n)=if(n*=10,Str(n\1,h(n-n\1)),"")
f(a,b)=Str(if(0>t=g(a)+g(b),t=-t;"-","")d=t\1,if(t-=d,Str("."h(t)),""))

```

Attempt This Online!

# Answer
> 2 votes
# JavaScript, 210 bytes

```
(a,b)=>([a,c='']=a.split`.`,[b,d='']=b.split`.`,m=c[k='length'],e=(o=(g=i=>BigInt(i+c.padEnd(l=m>d[k]?m:d[k],0)))(a)+g(b,c=d)+'')[k]-l,h=o.slice(0,e),i=o.slice(e).replace(/0+$/,''),(!h|h=='-'?h+0:h)+(i&&'.'+i))

```

```
(a,b)=>(                                    // Define function
  [a,c='']=a.split`.`,                      // a - integer part of number a
                                            // c - decimal part of number a (default value is '')

  [b,d='']=b.split`.`,                      // b - integer part of number b
                                            // d - decimal part of number b (default value is '')

  m=c[k='length'],                          // m - length of c
                                            // k - 'length' key

  e=(                                       // e - decimal point position
    o=                                      // o - sum of BigInts as string
      (g=i=>BigInt(                         // g - function which convert string to BigInt
                   i+
                   c.padEnd(
                        l=m>d[k]?m:d[k],    // l - the length of longest decimal part
                        0
                   )
            ))(a)+

                                            // c.padEnd(l, '0') - adding to the end of decimal
                                            // part as many zeros as it need to
                                            // be the length of 'l'`
                                            // i + c.padEnd(l, '0') - same number as in input
                                            // without decimal point and possibly
                                            // with trailing zeros

      g(b,c=d)+                             // now c is decimal part of number b

      ''                                    // added to convert BigInt to string
  )[k]-l,
  h=o.slice(0,e),                           // h - integer part of result

  i=o.slice(e).replace(/0+$/,''),           // i - decimal part of result

  (!h|h=='-'?h+0:h)                         // if h is empty string or minus
                                            // then add zero else do nothing

  +                                         // concatenate of integer part of result
                                            // and decimal part of result

  (i&&'.'+i)                                // if i is empty string then
                                            // return empty string else
)                                           // add leading dot

```

Try it:

```
f=(a,b)=>([a,c='']=a.split`.`,[b,d='']=b.split`.`,m=c[k='length'],e=(o=(g=i=>BigInt(i+c.padEnd(l=m>d[k]?m:d[k],0)))(a)+g(b,c=d)+'')[k]-l,h=o.slice(0,e),i=o.slice(e).replace(/0+$/,''),(!h|h=='-'?h+0:h)+(i&&'.'+i))

;[
    ['1', '1'], // '2'
    ['0', '0'], // '0'
    ['9', '1'], // '10'
    ['001.002', '3.400'], // '4.402'
    ['5', '-5.0'], // '0'
    ['2', '-2.5'], // '-0.5'
    ['12345', '67890'], // '80235'
    ['-50.6', '20.53'], // '-30.07'
    ['-001.00', '00100'], // '99'
    ['-00.100', '-0.20'], // '-0.3'
    ['0.1', '0.2'], // '0.3'
    ['1000000000000', '-0.000000000001'], // '999999999999.999999999999'
].map(x => {
    console.log(f(x[0], x[1]));
    console.log(f(x[1], x[0]));
})
```

# Answer
> 2 votes
# Dyalog APL, 7 bytes

```
+/⍎¨

```

Try it online!

**Explanation:**

```
+/⍎¨
   ¨  ⍝ Map each element in the array
  ⍎   ⍝ Execute expression, which converts from string to integer
 /    ⍝ Reduce
+     ⍝ Sum

```

# Answer
> 2 votes
# PHP 8.x + BC Math, 46 bytes

It's a bit longer than expected, but does the job.

```
fn($a,$b)=>rtrim(rtrim(bcadd($b,$a,99),0),'.')

```

This creates an anonymous function that returns the expected result.

---

# How does it work?

It uses the `bcadd` function to do all the math, using an obnoxiously high scale, just to be safe.

That function accepts 2 strings and returns a string with the calculations made.

After that, removes all 0's from the right, then the period (.).
If none is found, does nothing to the result.

---

You can try it on here - with testcases:
https://onlinephp.io?s=VVHNSsNAED4byDvMIbAJbLabpH9RY\_EgeBDswVsIkiYbItSmJNsiiG8gePGo7-Hz-AK-gpPduK17mJn9vvnmhzlfbOutbdnWaASX6zVI0Uko8k50tuU8QQKpbZ2kJCAUtAlJRhXE-99gBig2WYHBOA8Y52EPRmzMlWCMgakz6RF\_wv6XUgI\_ZJrl6AciCKOxAqezeaw0cx5GhvYnnE3VnKiJlDjijM8Mr-dRvXiggzg-YtkAYs\_wL4jMMkxth5R2hkDR4Q2qIyTQbQ6PHX9IZlvZ2XCEu1pA0ZQCZJ1LKBvRQSd3VYXnqDZ4j2rjOjl1Vl5y0cr24dHVdlXkZek6K4pkHHuUe5Qw4qmqVdOKvKhdvGfegbP3nnFmpxXdbi2xotOX3Kc8o8ilQdaLTkRRN2BykqSnwgwWQL4\_3n--3gicYvj52i8GPqAbkiksr5f3V7c3WOXlFw%2C%2C&v=8.2.1

Extremely long URL to avoid saving it on the website

# Answer
> 2 votes
# bc, 162 bytes

```
x=a+b;y=x/1;if(y==x)x=y;if(x==0||x<=-1||x>=1){print x,"\n";return}
if(scale(x)>1&&x*10^length(x)%10==0){scale=1;y=x/1.0;x=y};if(x<0)print "-0",-x else print "0",x

```

Try it online!. Adapted from a great s.o answer.

Explanation

```
x=a+b                       starting out simple
y=x/1;if(y==x)x=y           drop trailing 0's after the decimal
                            (99.00 -->  99 )
if(x==0||x<=-1||x>=1)       if x==0 or abs(x)>=1 then just print it
return                      preferable to `else{...}`, IMO.
                            From now on x is between -1 and 1.
if(scale(x)>1               if x has an gnarly decimal
  &&x*10^length(x)%10==0)   and the last digit is 0
{scale=1;y=x/1.0;x=y}       drop trailing 0's & keep significant digits
                            (-.300 -->  -.3)
if(x<0)print "-0",-x        (-.3   --> -0.3)
else print "0",x            ( .5   -->  0.5)

```

# Answer
> 1 votes
# Factor \+ `decimals`, 48 bytes

```
[ [ string>decimal ] bi@ D+ unparse " " split1 ]

```

```
[ string>decimal ] bi@   ! convert both inputs to the decimal data type (arbitrary size decimals)
D+                       ! add them together
unparse                  ! convert prettyprinted format to string
" " split1               ! remove DECIMAL: prefix

```

# Answer
> 0 votes
tcl:

expr $A+$B

Tcl has no concept of a "number"; everything is a string. Some strings can be interpreted as numbers, which is what "expr" does above. Literally "take the contents of the variables "A" and "B", put a "+" between the two and treat the result as interpretable as an expression (and return the result of that expression)"

---
Tags: code-golf, string, number
---


title: Count the number of disjoint 11 blocks

text:
# Question
Title: Count the number of disjoint 11 blocks
The task is to count the number of disjoint `11` blocks in a 64-bit word, using the minimum number of straight-line instructions. That is, how many nonoverlapping neighbored pairs of 1-bits can be found.

## Examples

(imagine leading zeros to fill up to 64 bits)

```
      Input Output
     111111      3
    1110111      2
11110010111      3

```

Here is a possible implementation (that would not be a valid answer since it uses a loop and a condition):

```
uint64_t f(uint64_t x) {
    uint64_t n = 0;
    while (x)
        if ((x & 3) == 3)
            ++n, x >>= 2;
        else
            x >>= 1;
    return n;
}

```

## Scoring

The goal is to minimize the number of instructions. Instructions allowed are only the basic bitwise and arithmetic operators (`|`, `&`, `^`, `+`, `-`, `~`, `<<`, `>>` (arithmetic shift)) plus `popcount` (count the number of bits set in a word), `clz` (count leading zeroes), and `ctz` (count trailing zeroes). Also, `*` and `/` are allowed with a cost of 5 and 25 instructions, respectively. Using 64-bit constants is free. No loops, conditions, function calls etc. are allowed. Example of a three-instruction function that makes it easy to count the number of instructions:

```
uint64_t f(uint64_t x) {
    uint64_t t0 = x ^ 0xff00ff00ff00ff00;
    uint64_t t1 = t0 - 1;
    uint64_t t2 = popcount(t1);
    return t2;
}

```

but it's also fine to present it in more readable form.

**EDIT:** now also allowing `clz`, `ctz`, `*`, and `/`.

# Answer
> 11 votes
# 5 ops

```
E = int('01'*32, 2)  # ...01010101

def f(n):
 r = (n ^ E) + E    # 2 ops
 t = n & (E ^ r)    # 2 ops
 return popcount(t) # 1 op

```

Try it online!

**6 ops**

```
E = int('01'*32, 2)  # ...01010101
O = int('10'*32, 2)  # ...10101010

def f(n):
 r = (n << 1) | E       # 2 ops
 t = n & (O ^ (r - n))  # 3 ops
 return popcount(t)     # 1 op

```

Try it online!

# Answer
> 5 votes
# 11 ops

```
uint64_t f(uint64_t x) {                      // 11111011110
    uint64_t notx = ~x; // odd ^ even         // 00000100001
    uint64_t bit = notx & (x>>1);             // 00000100001
    uint64_t odd = bit & 0x5555555555555555;  // 00000000001
    uint64_t even = ~bit | 0x5555555555555555;// 11111011111
    uint64_t cov1 = notx; // odd ^ even       // 00000100001
    uint64_t cov2 = odd + even;               // 11111100000
    uint64_t cov = cov1 ^ cov2;               // 11111000001
    uint64_t mask = cov ^ 0x5555555555555555; // 01010010100
    uint64_t res = mask & x;                  // 01010010100
    return __builtin_popcountll(res);         // (4)
}

```

Try it online!

Verify through 0..65535

# Answer
> 4 votes
# 28 ops

```
uint64_t f(uint64_t x) {
    uint64_t a = x & (x >> 1);
    uint64_t b = a & (~a >> 1 | a >> 2);
    uint64_t c = b & (~b >> 1 | b >> 4);
    uint64_t d = c & (~c >> 1 | c >> 8);
    uint64_t e = d & (~d >> 1 | d >> 16);
    uint64_t f = e & (~e >> 1 | e >> 32);
    return popcount(f);
}

```

Try it online!

---
Tags: binary, atomic-code-golf, bitwise
---