title: Am I an insignificant array?

text:
# Question
Title: Am I an insignificant array?
An *insignificant array* is an array of positive integers, where the absolute differences between consecutive elements are all smaller than or equal to **1**.

For example, the following array is insignificant:

```
[1, 2, 3, 4, 3, 4, 5, 5, 5, 4]

```

Because the corresponding (absolute) differences are:

```
[1, 1, 1, 1, 1, 1, 0, 0, 1]

```

Which are all smaller than or equal to **1**.

---

Your task is to determine whether a given array of integers is insignificant.

* You may assume that the array always contains at least two elements.
* Standard input and output rules apply. You may take input (and output) in any reasonable format.
* Default Loopholes are forbidden.
* The truthy / falsy values have to be distinct and consistent.
* This is , so shortest answer in bytes wins.

# Test cases

```
Input -> Output

[1, 2, 3, 4, 3, 4, 5, 5, 5, 4] -> true
[1, 2, 3, 4, 5, 6, 7, 8, 9, 8] -> true
[3, 3, 3, 3, 3, 3, 3]          -> true
[3, 4, 4, 4, 3, 3, 3, 4, 4, 4] -> true
[1, 2, 3, 4]                   -> true
[5, 4, 3, 2]                   -> true
[1, 3, 5, 7, 9, 7, 5, 3, 1]    -> false
[1, 1, 1, 2, 3, 4, 5, 6, 19]   -> false
[3, 4, 5, 6, 7, 8, 7, 5]       -> false
[1, 2, 4, 10, 18, 10, 100]     -> false
[10, 20, 30, 30, 30]           -> false

```

I used the values `true` and `false`.

# Answer
> 26 votes
# Jelly, 3 bytes

```
IỊẠ

```

**Try it online!**

# How?

Just the perfect challenge for Jelly.

```
IỊẠ   Full program.

I     Increments; Get the difference between consecutive elements.
 Ị    Insignificant; return abs(number) ≤ 1.
  Ạ   All; returns 1 if all the elements are truthy, 0 otherwise.

```

# Answer
> 21 votes
# JavaScript (ES7), ~~33~~ 29 bytes

*Saved 4 bytes thanks to @JohanKarlsson*

```
a=>!a.some(v=>(a-(a=v))**2>1)

```

### How?

When coerced to `Number`, arrays of at least two elements are evaluated to `NaN`. By re-using the input ***a*** as the variable holding the previous value, the first iteration of ***some()*** always results in ***(\[v0, v1, ...\] - a\[0\]) \** 2 = NaN***, no matter the value of ***a\[0\]***. So, the first test is always falsy and the actual comparisons start at the 2nd iteration, just as they're meant to.

### Test cases

```
let f =

(a,p)=>!a.some(v=>(p-(p=v))**2>1)

console.log(f([1, 2, 3, 4, 3, 4, 5, 5, 5, 4])) // true
console.log(f([1, 2, 3, 4, 5, 6, 7, 8, 9, 8])) // true
console.log(f([3, 3, 3, 3, 3, 3, 3]         )) // true
console.log(f([3, 4, 4, 4, 3, 3, 3, 4, 4, 4])) // true
console.log(f([1, 2, 3, 4]                  )) // true
console.log(f([5, 4, 3, 2]                  )) // true
console.log(f([1, 3, 5, 7, 9, 7, 5, 3, 1]   )) // false
console.log(f([1, 1, 1, 2, 3, 4, 5, 6, 19]  )) // false
console.log(f([3, 4, 5, 6, 7, 8, 7, 5]      )) // false
console.log(f([1, 2, 4, 10, 18, 10, 100]    )) // false
console.log(f([10, 20, 30, 30, 30]          )) // false
```

# Answer
> 11 votes
# Python 3, 40 bytes

```
f=lambda n,*t:t==()or-2<n-t[0]<=1==f(*t)

```

Try it online!

# Answer
> 9 votes
# Haskell, ~~34~~ 33 bytes

```
all((<2).abs).(zipWith(-)=<<tail)

```

Try it online! *-1 byte thanks to @user1472751*

---

The point-free solution is ~~one~~ ~~two~~ again only one byte (*thanks to -1 byte from @Dennis*) shorter than the recursive approach:

```
f(a:b:r)=2>(a-b)^2&&f(b:r)
f _=1>0

```

Try it online!

# Answer
> 9 votes
## Mathematica, 24 bytes

```
Max@Abs@Differences@#<2&

```

# Answer
> 8 votes
# Octave, 21 bytes

```
@(x)all(diff(x).^2<2)

```

Anonymous function that inputs a numeric vector and ouputs `1` if insignificant or `0` otherwise.

**Try it online!**

# Answer
> 7 votes
# Pyth, 6 bytes

```
._MI.+

```

**Verify all the test cases.**

---

# Pyth, 8 bytes

```
.A<R2aVt

```

Try it online!

# Explanation

```
._MI.+   Full program.

    .+   Deltas.
   I     Is invariant under...
._M      Mapping with Sign. 0 if n == 0, -1 if n < 0, 1 if n > 0.

```

---

```
.A<R2aVt    Full program.

      Vt    Vectorize function, applied on the input zipped with the tail of the input.
     a      Absolute difference.
  <R2       For each, check if it is smaller than 2.
.A          All.

```

# Answer
> 7 votes
# Python 2, 35 bytes

```
x=input()
while-2<x.pop(0)-x[0]<2:1

```

Exists with status code **1** for insignificant arrays, with status code **0** otherwise.

Try it online!

# Answer
> 6 votes
# Husk, 4 bytes

```
ΛεẊ-

```

Try it online!

Explanation:

```
ΛεẊ- 2-function composition
Λ    (x -> y):f -> [x]:x -> TNum: Check if f returns a truthy result for all elements of x
 ε    f: TNum:x -> TNum: Check if abs(x) <= 1 (shamelessly stolen from Jelly)
  Ẋ   x: (x -> x -> y):f -> [x]:x -> [y]: reduce each overlapping pair of x by f
   -   f: TNum:x -> TNum:y -> TNum: y - x

```

# Answer
> 6 votes
# Japt, 6 bytes

```
äa e<2

```

Try it online!

## Explanation

```
ä        Get all pairs of elements
 a       Take absolute difference of each pair
         This results in the deltas of the array
   e     Check if every element...
    <2   Is less than 2

```

# Answer
> 6 votes
# APL, 13 bytes

```
{×/(|2-/⍵)<2}

```

First APL answer \o/

Note: I am a bot owned by Hyper Neutrino. I exist mainly for chat testing.

# Explanation

```
{×/(|2-/⍵)<2}
{           }  Function; right argument is ⍵
   (     )     Bracketed Expression
       /       Reduce
     2         Every pair (two elements) of
        ⍵      ⍵
      -        Using subtraction
    |          Magnitude (Absolute Value)
          <2   For each element, is it less than two?
  /            Reduce over
 ×             Multiplication (Product) (All)

```

# Answer
> 5 votes
# 05AB1E, 5 bytes

```
¥Ä2‹P

```

Try it online!

**Explanation**

```
¥        # calculate deltas
 Ä       # absolute values
  2‹     # smaller than 2
    P    # product

```

# Answer
> 5 votes
# Perl 6, 25 bytes

```
{?(2>all(.[]Z-.skip)>-2)}

```

Try it online!

This should be pretty readable. The only less obvious thing here is that the zip operator `Z` will stop zipping when the shorter list is exhausted (we remove the first element of the list at the right) and that the empty subscript `.[]`, so called Zen slice, gives the whole list. `.skip` returns the list without the first element.

# Answer
> 5 votes
# Proton, 41 bytes

```
a=>all(-2<a[i]-a[i+1]<2for i:0..len(a)-1)

```

Try it online!

-16 bytes thanks to Mr. Xcoder
-2 bytes
-6 bytes thanks to Mr. Xcoder

# Answer
> 5 votes
# C# (.NET Core), ~~51~~ ~~45~~ 44 + 18 bytes

*-1 byte thanks to Jeppe Stig Nielsen*

```
a=>a.Zip(a.Skip(1),(x,y)=>x-y).All(x=>x*x<4)

```

Byte count also includes:

```
using System.Linq;

```

Try it online!

Explanation:

```
a =>                      // Take an array of integers as input
    a.Zip(                // Combine each element with corresponding one from:
        a.Skip(1),        //     the input array without first element
        (x, y) => x - y   //     get their difference
    )
    .All(x => x * x < 4)  // Check if all differences are less than 2
                          // (We only care about 0 and 1, and so happens that when they're squared, it works like Abs! Magic!)

```

# Answer
> 5 votes
# , ~~30~~ 26 bytes

```
cat(all(diff(scan())^2<2))

```

Try it online!

# Answer
> 5 votes
# Ohm v2, 4 bytes

```
Δ2<Å

```

Try it online!

# How?

```
Δ2<Å   ~ Full program.

Δ      ~ Absolute deltas.
 2<    ~ Is smaller than 2?
   Å   ~ Check if all elements are truthy.

```

# Answer
> 4 votes
# PowerShell, 62 bytes

```
param($a)$l=$a[0];($a|?{$_-$l-in1..-1;$l=$_}).count-eq$a.count

```

Try it online!

PowerShell doesn't have a `.map` or `.some` or similar command, so here we're individually checking each delta.

We take input `$a` and set `$l` equal to the first element. Then we loop through `$a` and take out each element where `|?{...}` the difference `$_-$l` is `-in` the range `1,0,-1`. We then set `$l` equal to the current element. So now we have a collection of elements where the delta between their previous neighbor is 1. We take the `.count` of that and check whether it's `-eq`ual to the `.count` of the array as a whole. If it is, then every delta is 1 or less, so it's an insignificant array. That Boolean result is left on the pipeline, and output is implicit.

# Answer
> 4 votes
# Factor, ~~48~~ 33 bytes

Saved 15 bytes thanks to @chunes!

```
[ dup rest v- vabs supremum 2 < ]

```

Try it online! (results are at the bottom)

`dup rest` makes a copy of the inputted sequence without the first element. `v-` subtracts that from the original sequence (\\$a\_n-a\_{n-1}\\$). Then `vabs` gets the absolute values of that. `supremum` finds the maximum value in the sequence, and `2 <` makes sure it's 0 or 1.

# Answer
> 3 votes
# Python 3, 45 bytes

```
lambda k:all(-2<x-y<2for x,y in zip(k,k[1:]))

```

**Try it online!** or **Try the test suite.**

Thanks to Jonathan Frech for -2 bytes.

# Answer
> 3 votes
# MATL, ~~6~~ 5 bytes

```
d|2<A

```

-1 byte thanks to *Giuseppe*

Try it online! or Verify all test-cases

# Answer
> 3 votes
# C, ~~61~~ 56 bytes

*Thanks to @scottinet for saving five bytes!*

```
r;f(a,n)int*a;{for(r=1;--n;r=(*a-*++a)/2?0:r);return r;}

```

Try it online!

# C (gcc), 47 bytes

```
r;f(a,n)int*a;{for(r=1;--n;r=(*a-*++a)/2?0:r);}

```

Try it online!

# Answer
> 3 votes
# Java (OpenJDK 8), 60 bytes

```
a->{int r=1,p=a[0];for(int i:a)r|=(r=p-(p=i))*r;return r<2;}

```

Try it online!

* 5 bytes thanks to @Nevay!

# Answer
> 3 votes
# anyfix, 9 bytes

```
I€A€2<»/&

```

Try it online!

```
I€A€2<»/&  Main Link
I          Deltas
 €         For each element
  A        Take its absolute value
   €  »    For each element
    2<     Is it less than two?
       /   Reduce over
        &  Logical AND

```

This is mostly a port of the 05AB1E solution except terrible because anyfix doesn't have autovectorization and other cool things

# Answer
> 3 votes
# Ruby, 36 35 33 bytes

```
->b,*a{a.all?{|x|(b-(b=x))**2<2}}

```

Takes the input array as individual arguments.

-1 byte thanks to MegaTom, -2 bytes thanks to Jordan.

Try it online!

# Answer
> 3 votes
# Julia 0.6, 21 bytes

```
~x=all(diff(x).^2.<2)

```

Try it online!

-1 byte thanks to MarcMush: pass a single argument to `all`

# Answer
> 2 votes
# Java (OpenJDK 8), 78 bytes

```
a->{int p=0,i=1;for(;i<a.length;p+=Math.abs(a[i]-a[i++-1])>1?1:0);return p<1;}

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), ~~37~~ 36 bytes

```
(a,u)=>!a.some(e=>(e-=(u=e))>1|e<-1)

```

Edit: Saved 1 byte by stealing @Arnauld's trick.

# Answer
> 2 votes
# Pyth, 7 bytes

```
._I#I.+

```

Test Suite

Returns true/false.

Explanation:

```
     .+ Deltas, returns differences between consecutive values.
._      Signum, returns the sign of a number (1, 0, or -1).  Note that this should
             be equal to the input for insignificant arrays.
  I     Tests if it is equal to the input...
   #    For each in the input, and filter out those that aren't...
    I   And make sure none have been filtered out.

```

# Answer
> 2 votes
## Mathematica, 34 bytes

```
Differences@#~MatchQ~{(1|0|-1)..}&

```

# Explanation

```
                                 & (* Function *)
Differences                        (* which takes the consecutive differences*)
           @#                      (* of the input list *)
             ~MatchQ~              (* and returns whether it matches *)
                     {(1|0|-1)..}  (* a list consisting of one or more 1s, 0s, or -1s *)

```

# Answer
> 2 votes
## TI-Basic, ~~6~~ 7 bytes

```
prod(2>abs(ΔList(Ans

```

or, 5 bytes if errors count as valid return value (returns `ERR:ARGUMENT` if insignificant, else `ERR:DOMAIN`)

```
augment(sin⁻¹(ΔList(Ans

```

# Answer
> 2 votes
# Swift 4, 52 bytes

```
{!zip($0.dropFirst(),$0).map(-).contains{1<abs($0)}}

```

Test suite:

let isInsignificant: (_ array: [Int]) -> Bool = {!zip($0.dropFirst(),$0).map(-).contains{1<abs($0)}}

let testcases: [(input: [Int], expected: Bool)] = [
    (input: [1, 2, 3, 4, 3, 4, 5, 5, 5, 4], expected:  true),
    (input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 8], expected:  true),
    (input: [3, 3, 3, 3, 3, 3, 3],          expected:  true),
    (input: [3, 4, 4, 4, 3, 3, 3, 4, 4, 4], expected:  true),
    (input: [1, 2, 3, 4],                   expected:  true),
    (input: [5, 4, 3, 2],                   expected:  true),
    (input: [1, 3, 5, 7, 9, 7, 5, 3, 1],    expected: false),
    (input: [1, 1, 1, 2, 3, 4, 5, 6, 19],   expected: false),
    (input: [3, 4, 5, 6, 7, 8, 7, 5],       expected: false),
    (input: [1, 2, 4, 10, 18, 10, 100],     expected: false),
    (input: [10, 20, 30, 30, 30],           expected: false),
]

for (caseNumber, testcase) in testcases.enumerated() {
    let actual = isInsignificant(testcase.input)
    assert(actual == testcase.expected,
        "Testcase #\(caseNumber) \(testcase.input) failed. Got \(actual), but expected \(testcase.expected)!")
    print("Testcase #\(caseNumber) passed!")
}
```
</code></pre>

# Answer
> 2 votes
## Clojure, 35 bytes

```
#(every? #{-1 0 1}(map -(rest %)%))

```

How neat is that?

# Answer
> 2 votes
# , 20 19 bytes

```
i=.[:*/2>[:|2&(-/\)

```

I defined it as a verb, which adds 3 bytes to the total length.

## Explanation

```
2&(-/\) finds the difference between two consecutive elements
| takes the absolute value
[: caps the fork so that the result is propagated onwards
2> finds if the values are smaller than 2
*/ calculates the product of all the elements, so yields 1 only if all are 1s
[: caps the fork so that the result is propagated onwards

```

## Example:

```
   i 1 3 5 7 9 7 5 3 1
0

```

Try it online

# Answer
> 2 votes
## F#, 56 bytes

```
let f a=Seq.forall(fun(x,y)->abs(x-y)<2)(Seq.pairwise a)

```

# Answer
> 2 votes
# K (ngn/k), ~~15~~ 13 bytes

-2 bytes from @ngn's improvements

```
&/2>#'!'1_-':

```

Try it online!

* `-':` subtract each value in the (implicit) input from its predecessor
* `1_` drop the first result
* `#'!'` take the absolute value (literally, take the count of the range of each value; e.g. `1` -\> `,0`, `-2` -\> `-2 -1`)
* `&/2>` are all the absolute values smaller than 2?

# Answer
> 2 votes
# Julia, 17 bytes

```
!x=diff(x)⊆-1:1

```

Attempt This Online!

# Answer
> 2 votes
# Uiua, 8 bytes

```
≅±.≡/-◫2

```

Try it!

```
≅±.≡/-◫2
      ◫2  # windows of length two
   ≡/-    # subtract second column from first (differences)
  .       # duplicate
 ±        # sign (pervasive across array)
≅         # do they match?

```

# Answer
> 1 votes
# Perl 5, 38 + 2 (-ap) = 40 bytes

```
$_&&=abs$i-$F[-1]<2while($i=pop@F)&&@F

```

Try it online!

# Answer
> 1 votes
# RProgN 2, 8 bytes

```
{-â2<}á*

```

## Explained

```
{-â2<}á*
{    }á     # Fold the input by the function
 -          # Subtract, get the difference.
  â         # Absolute
   2<       # Is less than 2.
       *    # Get the product, 1 for truthy, 0 for falsey.

```

Try it online!

# Answer
> 1 votes
# Common Lisp, 53 bytes

```
(lambda(a)(every(lambda(x y)(< -2(- x y)2))a(cdr a)))

```

Try it online!

# Answer
> 1 votes
# Jq 1.5, ~~42~~ 41 bytes

```
all(keys[1:][]as$i|.[$i]-.[$i-1]|.*.;.<2)

```

Explained

```
all(                   # true if all values from
    keys[1:][] as $i   # scanning input indices starting at second element
  | .[$i]-.[$i-1]      # calculate differences between successive elements
  | .*.                # square the difference
; . < 2                # are < 2
)

```

Sample Run

```
$ jq -Mc 'all(keys[1:][]as$i|.[$i]-.[$i-1]|.*.;.<2)' data.json
true
true
true
true
true
true
false
false
false
false
false

$ echo -n 'all(keys[1:][]as$i|.[$i]-.[$i-1]|.*.;.<2)' | wc -c
  41

```

# Answer
> 1 votes
# Excel VBA, 55 Bytes

Anonymous VBE immediate window function that takes input from range `[1:1]` and outputs to the VBE immediate window

```
[2:2]="=IfError(If(B1=0,0,ABS(B1-A1)),0)":?[Max(2:2)>1]

```

# Answer
> 1 votes
# Pushy, 13 bytes

```
$2d-|v.;Og2<#

```

**Try it online!**

```
                 \ Implicit: Input on stack
$      ;         \ While there are items left on stack:
 2d-|            \   Get the absolute difference of the last two integers
     v           \   Send this to the second stack
      .          \   Pop the last item

        O        \ Go to the second stack (list of differences)
         g       \ Sort ascendingly (largest item last)
          2<#    \ Check if it is smaller than 2 (print 1/0 accordingly)

```

# Answer
> 1 votes
# PHP, 85 bytes

```
function a($p){$r=1;foreach($p as$k=>$q)if($p[$k+1]&&abs($p[$k+1]-$q)>1)$r=0;echo$r;}

```

Try it online!

It can probably be golfed some more, but it's a start.

# Answer
> 1 votes
# Add++, 16 bytes

```
L,vbUÑ_€|2ª>

```

Try it online!

## How it works

```
L,		; Create a lambda function
		; Example argument: 	    ['[1 2 3 4 3 4 5 5 5 4]']
	vbU	; Evaluate as list; STACK = [1 2 3 4 3 4 5 5 5 4]
	Ñ_	; Deltas;	    STACK = [1 1 1 -1 1 1 0 0 -1]
	€|	; Absolute values;  STACK = [1 1 1 1 1 1 0 0 1]
	2ª>	; All less than 2;  STACK = [1]

```

# Answer
> 1 votes
# Regex (ECMAScript), 27 bytes

```
^(x(x*)(,(?=\2x?x?\b)|$))*$

```

Try it online!

Input is a list of positive unary numbers separated by `,`. Each one is a string of `x`s whose length represents the number.

```
^
(
    x(x*)         # \2 = this element - 1
    # Assert that either the next element is in the range \2 to \2+2 inclusive,
    # or that we've reached the end and there are no more elements.
    (
        ,         # Skip to the next element
        (?=       # look ahead to the next element to make the following assertion:
            \2    # subtract \2 from it
            x?x?  # subtract any number from 0 to 2 from it
            \b    # assert that we matched the exact number
        )
    |
        $
    )
)*
$

```

# Regex (ECMAScript), 21 bytes

```
\b(x+)(xx+,|,xx+)\1\b

```

Try it online!

Returns a non-match if the array is insignificant, and a match otherwise (i.e., its boolean result is inverted).

If this solution were converted to match=true logic, it would be `^(?!.*\b(x+)(xx+,|,xx+)\1\b)` **(28 bytes)**.

```
           # No anchor; can match starting anywhere
\b         # Assert word boundary, i.e. either the start of the string before
           # an "x", a position after an "x" and before a ",", a position
           # after a "," and before an "x", or the end of the string after an
           # "x".
(x+)       # \1 = any substring of "x"es
(
    xx+,   # 2 or more "x"es followed by ","
|          # or
    ,xx+   # "," followed by 2 or more "x"es
)
\1         # Match what was captured in \1
\b         # Assert word boundary

```

# Answer
> 1 votes
# Desmos, 46 bytes

```
\left\{max(abs(n[2,...,n.length]-n))<2\right\}

```

View on Desmos!

This is a rare case where I think using `\left\{\right\}` is more efficient than not.

# Answer
> 1 votes
# Vyxal, ~~5~~ 4 bytes

```
¯vṅA

```

Try it Online!

```
¯vṅA
¯    # delta (consecutive diff)
 vṅ  # abs(a) ≤ 1
   A # all truthy?

```

-1 thx to @Sʨɠɠan

# Answer
> 1 votes
# Pyth, 6 bytes

```
._MI.+

```

Test suite

##### Explanation:

```
._MI.+  | Full code
._MI.+Q | with implicit variables
--------+------------------------------------
    .+Q | Differences of the input
   I    | Is it invariant over:
._M     |  Replace each element with its sign

```

# Answer
> 1 votes
# Rust, 43 bytes

```
|a|a.windows(2).all(|s|(s[1]-s[0]).abs()<2)

```

Try it online!

A `fn(&[i8])->bool`.

# Answer
> 1 votes
# Pyt, 5 bytes

```
₋Å2<Π

```

Try it online!

```
₋           implicit input; get differences
 Å          Åbsolute value
  2<        is each difference less than 2?
    Π       product; implicit print

```

# Answer
> 1 votes
# Pip, 11 bytes

```
2>M:BAD_MPg

```

Attempt This Online!

### Explanation

```
2>M:BAD_MPg
          g  ; List of command-line arguments
        MP   ; Map to each pair of adjacent elements:
     AD      ;  Absolute difference between
    B        ;  the second and
       _     ;  the first
  M:         ; Get the max of that list
2>           ; 1 (truthy) if the max is less than 2; 0 (falsey) otherwise

```

# Answer
> 1 votes
# Thunno, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
z[ZA2<P

```

Attempt This Online!

Outputs `0` for False and `1` for True.

#### Explanation

```
z[ZA2<P  # Implicit input
z[       # Differences of the input
  ZA     # Absolute value of each
    2<P  # Are they all less than 2?
         # Implicit output

```

# Answer
> 1 votes
# Excel, ~~35~~ 33 bytes

```
=AND(ABS(DROP(ζ,1)-DROP(ζ,-1))<2)

```

*2 bytes saved under the assumption that the input can be arbitrarily chosen so as to be a vertical vector.*

# Answer
> 1 votes
# Nekomata \+ `-e`, 4 bytes

```
∆A2<

```

Attempt This Online!

```
∆A2<
∆       Differences
 A      Absolute value
  2<    Is less than 2?

```

---

# Nekomata \+ `-e`, 4 bytes

```
∆:±=

```

A port of @Mr. Xcoder's Pyth answer.

Attempt This Online!

```
∆:±=
∆       Differences
 :      Duplicate
  ±     Sign
   =    Equal?

```

# Answer
> 1 votes
# Lua, 57 bytes

```
for i=2,#arg do b=b or 1<(arg[i]-arg[i-1])^2 end print(b)

```

Try it online!

Outputs `false` if the array is insignificant, or `true` if it is not.

# Answer
> 0 votes
# Python 3, 54 bytes

2 bytes thanks to Jonathan Frech.

```
lambda a:all(-2<a[i]-a[i+1]<2for i in range(len(a)-1))

```

Try it online!

# Answer
> 0 votes
# Clojure, 36 bytes

```
#(every? #{-1 0 1}(map - %(rest %)))

```

Try it online!

# Answer
> 0 votes
# 8th, ~~66~~ ~~49~~ 55 bytes

**Code**

```
1 >r ( n:- abs dup 1 > if rdrop 0 >r then ) a:y drop r>

```

**SED** (Stack Effect Diagram) is: `a -- f`

**Explanation**

This code leaves `1` on TOS if array is *insignificant*, otherwise it leaves `0`. Here the ungolfed version:

```
1 >r                                           \ suppose array is insignificant
( n:- n:abs dup 1 n:> if rdrop 0 >r then ) a:y \ compute corresponding (absolute) differences and check if difference is > 1
drop r>                                        \ clean stack and put result on TOS

```

We could immediately exit from loop with `break` when array is *significant*, but in this case we waste 6 bytes.

# Answer
> 0 votes
# **Python 3, 49 bytes**

```
lambda l:all(abs(j-i)<=1 for i,j in zip(l,l[1:]))

```

# Answer
> 0 votes
# Pyth, ~~15~~ 12 bytes

Works pretty simply. `T` or 10 as a boolean is `True`

```
V.+Q=&T<N2)T

```

Explanation:

```
V.+Q        In the difference map of the input...
    =&T<N2) T = T && the current item is less than 2, and close the loop
T           Print J

```

Test Suite

# Answer
> 0 votes
**Scheme - 89 bytes**

```
(define (f n) (if (not (empty? n)) (and (<= (abs (- (cadr n) (car n))) 1) (f (cdr n))) 1)

```

# Answer
> 0 votes
# Casio-Basic, 28 bytes

```
judge(max(abs(⊿list(n)))<2

```

It's nice that the fx-CP400 has a built-in for cumulative differences. Not so nice that you need to use `judge` to force it to check whether the resulting value is less than 2.

27 bytes for the function ( is two bytes), +1 to enter `n` in the argument list.

# Answer
> 0 votes
# Pxem, Filename: 40 bytes + Content: 0 bytes = 40 bytes.

* Filename (escaped): `._\001.-.c._.t.w\001.-._.c.m.-\001.x.d.a.t.c.aY.o`
* Content: empty

## Usage

Input is from STDIN; output from STDOUT. First positive integer N for input represents number of items in list. Then integers c1, c2, ..., cN represents each item of the list. Each input has to be separated by one or more s.

An output of `Y` represents truthy, and no output falsey.

### Input example

List `[1, 2, 3, 4, 3, 4, 5, 5, 5, 4]` is:

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

```

## With comments

```
XX.z
.a._\001.-.cXX.z # push N; decrement it
.a._.tXX.z # push c1; heap<-c1
.a.w\001.-XX.z # while N!=0; do N--
  .a._.c.m.-\001.xXX.z # push ci; if abs(ci-heap); then
    .a.dXX.z # exit
  .a.aXX.z # fi
  .a.tXX.z # heap=ci
.a.c.aXX.z # done
.aY.oXX.z # putchar o
.a

```

## Link

Try it online!

# Answer
> 0 votes
# Factor, 28 bytes

```
[ [ - [-1,1]? ] monotonic? ]

```

Try it online!

`monotonic?` is a combinator that tests if a quotation returns true for every pair of adjacent elements in a sequence.

* `-` Subtract.
* `[-1,1]?` Is it between -1 and 1 inclusive? (This is just the name of a word, like most everything in Factor.)

# Answer
> 0 votes
# Arturo, 36 bytes

```
$[a][n:a\0every? a'x[2>abs n-x n:x]]

```

Try it

# Answer
> 0 votes
# Stax, 8 bytes

```
┘ε≡}◄ï╖Z

```

Run and debug it

Link includes all test cases.

Unpacked:

# Stax, 10 bytes

```
:-{|a2<m:*

```

Run and debug it

```
:-          # pairwise differences/deltas
  {     m   # mapped by
   |a       # absolute value of n
     2<     # is less than 2
         :* # product of array (essentially all(a))

```

# Answer
> 0 votes
# Kamilalisp, 31 bytes (APL385 SBCS)

```
$(∧?∘⌹‡⍡ 2 $(> 2)∘abs∘$(⌿⊙← -))

```

Attempt This Online!

---
Tags: code-golf, number, array, decision-problem
---


title: Write a variadic fixed point combinator

text:
# Question
Title: Write a variadic fixed point combinator
A fixed-point combinator is a higher order function \\$\mathrm{fix}\\$ that returns the fixed point of its argument function. If the function \\$f\\$ has one or more fixed points, then $$\mathrm{fix} f=f(\mathrm{fix} f).$$ The combinator \\$Y\\$ has such properties. Encoded in lambda calculus: $$Y=\lambda f.(\lambda x.f(x x))\ (\lambda x.f (x x))$$ You can extend a fixed-point combinator to find the fixed point of the \\$i\\$-th function out of \\$n\\$ given functions. $$ \mathrm{fix}\_{i,n}f\_1\dots f\_n=f\_i(\mathrm{fix}\_{1,n}f\_1\dots f\_n)\dots(\mathrm{fix}\_{n,n}f\_1\dots f\_n) $$ As an extension to the \\$Y\\$ combinator:

\begin{alignat\*}{2} Y\_{i,n}=\lambda f\_1\dots f\_n.&((\lambda x\_1\dots x\_n.f\_i&&(x\_1x\_1\dots x\_n)\\ & && \dots\\ & && (x\_nx\_1...x\_n)))\\ &((\lambda x\_1\dots x\_n.f\_1&&(x\_1x\_1\dots x\_n)\\ & && \dots\\ & && (x\_nx\_1...x\_n)))\\ &\dots\\ &((\lambda x\_1\dots x\_n.f\_n&&(x\_1x\_1\dots x\_n)\\ & && \dots\\ & && (x\_nx\_1...x\_n))) \end{alignat\*}

Example: \begin{alignat\*}{3} Y\_{1,1}&=Y && &&&\\ Y\_{1,2}&=\lambda f\_1f\_2.&&((\lambda x\_1x\_2.f\_1&&&(x\_1x\_1x\_2)\\ & && &&& (x\_2x\_1x\_2))\\ & &&((\lambda x\_1x\_2.f\_1&&&(x\_1x\_1x\_2)\\ & && &&& (x\_2x\_1x\_2))\\ & &&((\lambda x\_1x\_2.f\_2&&&(x\_1x\_1x\_2)\\ & && &&& (x\_2x\_1x\_2)) \end{alignat\*}

**Your task** is to write a *variadic* fixed-point combinator \\$\mathrm{fix}^\*\\$ that finds and returns the fixed-points of all given functions. $$ \mathrm{fix}^\*f\_1\dots f\_n=\langle\mathrm{fix}\_{1,n}f\_1\dots f\_n,\dots,\mathrm{fix}\_{n,n}f\_1\dots f\_n\rangle $$ While the details are up to you, I suggest your program accepts a list of functions and returns a list of their fixed points.

**For example**, take the following pseudo-Haskell functions your program should be able to solve (basically \\$\mathrm{fix}\_{i,2}\\$):

```
-- even/odd using fix* with lambdas as function arguments
f = (\f g n -> if n == 0 then True else (g (n - 1)))
g = (\f g n -> if n == 0 then False else (f (n - 1)))
isEven = head $ fix* [f,g]
isOdd = tail $ fix* [f,g]

-- mod3 using fix* with lists as function arguments
h1 [h1, h2, h3] n = if n == 0 then 0 else h2 (n - 1)
h2 [h1, h2, h3] n = if n == 0 then 1 else h3 (n - 1)
h3 [h1, h2, h3] n = if n == 0 then 2 else h1 (n - 1)
mod3 = head $ fix* [h1, h2, h3]

```

**Example (ungolfed) implementation**:

> Bruijn: `y* [[[0 1] <$> 0] [[1 <! ([[1 2 0]] <$> 0)]] <$> 0]`

**Rules**:

* Use any language you like, as long as `fix*` can accept functions and return their fixed points in your preferred format
* `code-golf`, the shortest implementation in bytes wins
* You can assume a fixed point exists for every given function, you *do not* need to solve the halting problem
* **Bonus**: Subtract 10 from your byte count if your solution does not use recursion (i.e. does not use the feature of your language that's typically responsible for recursion; fixed-point combinators are allowed)
* Have fun!

**Related questions**:

# Answer
> 5 votes
# , 24 bytes

```
y=\(a)Map(\(x)x(y(a)),a)

```

Attempt this Online!

A recursive function that takes a list of functions and returns a list of functions. The input list of functions should be a list of mutually recursive functions. Each function within this list should take a list of functions as an argument, and return a function that makes use of one or more members of the function list.

Inspiration taken from the Haskell answer in Bubbler’s comment, as well as @KevinCruijssen’s Java answer.

Examples shown in the ATO link above and below are even/odd, mod 3 and Collatz problem.

```
even_odd_fix = list(
 is_even=\(func)\(n)!n||func$is_odd(n-1),
 is_odd=\(func)\(n)!!n&&func$is_even(n-1)
)

mod3_fix = list(
 is_0_mod3 = \(func)\(n)!n||func$is_2_mod3(n-1),
 is_1_mod3 = \(func)\(n)!!n&&func$is_0_mod3(n-1),
 is_2_mod3 = \(func)\(n)!!n&&func$is_1_mod3(n-1)
)

# Somewhat contrived mutually recursive list of functions to determine how many steps of the Collatz procedure to get to 1
coll_fix = list(
 \(func)\(n,d=0)if(n==1)d else func[[2+n%%2]](n,d+1),
 \(func)\(n,d)func[[1]](n/2,d),
 \(func)\(n,d)func[[1]](3*n+1,d)
)

even_odd = y(even_odd_fix)
mod3 = y(mod3_fix)
collatz_depth = y(coll_fix)[[1]]

```

# Answer
> 2 votes
# Java 8, 170 bytes

```
interface C{Object t(Object o);}interface F{C f();}interface P{C c(F[]f);static F[]g(P[]a){return java.util.Arrays.stream(a).map(p->(F)()->p.c(g(a))).toArray(F[]::new);}}

```

Based on *@user*'s Java answer for the related *Implement Fix2 combinator* challenge, as well as my Java answer for the related *Golfed fixed point combinator* challenge.

**Explanation:**

```
interface C{           // Completed Function interface
  Object t(Object o);} //  Using a function that transforms a given Object

interface F{           // Function interface
  C f();}              //  A wrapper to pass the 'Completed Function' as function

interface P{           // Program interface
  C c(F[]f);           //  Which takes an array of 'Function's as argument,
                       //  and returns a 'Completed Function'

  static F[]g(P[]a){   //  Recursive function that accepts an array of 'Program's as argument,
                       //  and returns an array of 'Function's
    return java.util.Arrays.stream(a)
                       //   Convert the given 'Program's-array to a generic Stream
      .map(p->         //   Map each 'Program' in this Stream to:
             (F)       //    A casted 'Function' (necessary since it's a generic instead of typed Stream)
             ()->      //    which wraps:
               p.c(    //     A completed call to its own 'Program' interface
                 g(    //      Using a recursive call to its own function
                   a)) //      with the given 'Program's-array as argument
      .toArray(F[]::new);}}
                       //   After the map: convert the Stream to a 'Function's-array

```

The method to call is `P::g`, which takes an array of `P` as argument and returns an array of `F`. To obtain a completed function `C` from an `F`, we can call `F::f` on it. `P` represents the function to be fixed, and its method `c` takes `F` as argument to prevent immediate evaluation, returning a `C` that represents a complete function to transform a given Object `o` with `C`'s `t(o)`.

**Example even/odd implementation:**

```
P[] evenOddFix = {
  func -> n -> (int)n == 0 ? true : func[1].f().t((int)n-1),
  func -> n -> (int)n == 0 ? false : func[0].f().t((int)n-1)
};
F[] evenOddFunctions = P.g(evenOddFix);
C evenFunc = evenOddFunctions[0].f(),
  oddFunc = evenOddFunctions[1].f();
Object evenResult = evenFunc.t(input),
       oddResult = oddFunc.t(input);

```

Try it online.

# Answer
> 2 votes
# Python 3, ~~55~~ 51 bytes

```
y=lambda a:[(lambda x:lambda:x(y(a)))(x)for x in a]

```

Try it online!

A lambda taking a list of mutually recursive functions and returning a list of functions that return functions. Unlike R, Python doesn’t have lazy evaluation of function arguments so an extra step is needed to delay function evaluation from happening within the call to `y` itself; I think this is analogous to the Java answer from @KevinCruijsson.

The even odd and Collatz examples here look like this:

```
even_odd_fix = [
 lambda f:lambda n:n==0 or f[1]()(n-1),
 lambda f:lambda n:n!=0 and f[0]()(n-1)
]

collatz_fix = [
 lambda f:lambda n,d=0:d if n==1  else f[int(n%2+1)]()(n,d+1),
 lambda f:lambda n,d:f[0]()(n//2,d),
 lambda f:lambda n,d:f[0]()(3*n+1,d)
]

even_odd = [f() for f in y(even_odd_fix)]
collatz = y(collatz_fix)[0]()

[print(x, "Even:", even_odd[0](x), "Odd:", even_odd[1](x), "Collatz:", collatz(x)) for x in range(1,11)]

```

Note that the functions returned must be called without an argument to return the actual useful function.

# Answer
> 2 votes
# JavaScript (ES6), 25 bytes

```
g=a=>a.map(p=>_=>p(g(a)))

;h=g([a=>n=>!n||a[1]()(n-1),a=>n=>!!n&&a[0]()(n-1)]);for(i=0;i<6;i++)console.log(h.map(f=>f()(i)));
```

Port of @KevinCruijssen's Java answer.

# Answer
> 1 votes
# Scala, 161 bytes

Port of @Kevin Cruijssen'Java answer in Scala.

---

Golfed version. Try it online!

```
trait C{def t(o:Any):Any}
trait F{def f():C}
trait P{def c(func:Array[F]):C}
object P{def g(a:Array[P]):Array[F]={a.map(p=>new F{override def f():C=p.c(g(a))})}}

```

Ungolfed version. Try it online!

```
trait C {
  def t(o: Any): Any
}

trait F {
  def f(): C
}

trait P {
  def c(func: Array[F]): C
}

object P {
  def g(a: Array[P]): Array[F] = {
    a.map(p => new F { override def f(): C = p.c(g(a)) })
  }
}

object Main extends App {
  val evenOddFix: Array[P] = Array(
    new P { override def c(func: Array[F]) = new C { override def t(n: Any) = if (n.asInstanceOf[Int] == 0) true else func(1).f().t(n.asInstanceOf[Int]-1) } },
    new P { override def c(func: Array[F]) = new C { override def t(n: Any) = if (n.asInstanceOf[Int] == 0) false else func(0).f().t(n.asInstanceOf[Int]-1) } }
  )

  val evenOddFunctions: Array[F] = P.g(evenOddFix)
  val evenFunc = evenOddFunctions(0).f()
  val oddFunc = evenOddFunctions(1).f()

  for(input <- 0 to 5){
    val evenResult = evenFunc.t(input)
    val oddResult = oddFunc.t(input)
    println(s"Input: $input → Even: $evenResult; Odd: $oddResult")
  }
}

```

---
Tags: code-golf, math, functional-programming, lambda-calculus
---


title: Is this a Smith number?

text:
# Question
Title: Is this a Smith number?
# Challenge description

A **Smith number** is a **composite** number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer `N`, determine if it's a Smith number or not.

The first few Smith numbers are `4`, `22`, `27`, `58`, `85`, `94`, `121`, `166`, `202`, `265`, `274`, `319`, `346`, `355`, `378`, `382`, `391`, `438` (sequence A006753 in OEIS).

# Sample input / output

```
18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True

```

# Notes

* Your code can be a function (method) or a full working program,
* Instead of words like `True` and `False`, you can use any truthy and falsy values, as long as it's clear what they are,
* This is a challenge, so make your code as short as possible!

# Answer
# Python 2, ~~122~~ ~~115~~ ~~110~~ 106 bytes

```
n=m=input()
s=0
for d in range(2,n):
 while n%d<1:n/=d;s+=sum(map(int,`d`))
print n<m>s==sum(map(int,`m`))

```

Saved 4 bytes thanks to Dennis

Try it on ideone.com

### Explanation

Reads a number on stdin and outputs `True` if the number is a Smith number or `False` if it is not.

```
n=m=input()                  # stores the number to be checked in n and in m
s=0                          # initializes s, the sum of the sums of digits of prime factors, to 0
for d in range(2,n):         # checks all numbers from 2 to n for prime factors
 while n%d<1:                # while n is divisible by d
                             #   (to include the same prime factor more than once)
  n/=d                       # divide n by d
  s+=sum(map(int,`d`))       # add the sum of the digits of d to s
print                        # print the result: "True" if and only if
      n<m                    #   n was divided at least once, i.e. n is not prime
      >                      #   and m>s (always true) and
      s==sum(map(int,`m`))   #   s is equal to the sum of digits of m (the input)

```
> 10 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
Æfḟȯ.DFżDSE

```

Returns **1** for Smith numbers and **0** otherwise. Try it online! or verify all test cases.

### Background

`Æf` (prime factorization) and `D` (integer-to-decimal) are implemented so that `P` (product) and  (decimal-to-integer) constitute left inverses.

For the integers **-4** to **4**, `Æf` returns the following.

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

```

For the numbers **-10, -1, -0.5, 0, 0.5, 1, 10**, `D` returns the following.

```
-11   -> [-1, -1]
-10   -> [-1, 0]
 -1   -> [-1]
 -0.5 -> [-0.5]
  0   -> [0]
  0.5 -> [0.5]
  1   -> [1]
 10   -> [1, 0]
 11   -> [1, 1]

```

### How it works

```
Æfḟȯ.DFżDSE  Main link. Argument: n (integer)

Æf           Yield the prime factorization of n.
  ḟ          Filter; remove n from its prime factorization.
             This yields an empty array if n is -1, 0, 1, or prime.
   ȯ.        If the previous result is an empty array, replace it with 0.5.
     D       Convert all prime factors to decimal.
      F      Flatten the result.
        D    Yield n in decimal.
       ż     Zip the results to both sides, creating a two-column array.
         S   Compute the sum of each column.
             If n is -1, 0, 1, or prime, the sum of the prime factorization's
             digits will be 0.5, and thus unequal to the sum of the decimal array.
             If n < -1, the sum of the prime factorization's digits will be
             positive, while the sum of the decimal array will be negative.
          E  Test both sums for equality.

```
> 10 votes

# Answer
# Brachylog, 19 bytes

```
@e+S,?$pPl>1,P@ec+S

```

Try it online!

### Explanation

```
@e+S,                 S is the sum of the digits of the input.
     ?$pP             P is the list of prime factors of the input.
        Pl>1,         There are more than 1 prime factors.
             P@e      Split each prime factor into a list of digits.
                c     Flatten the list.
                 +S   The sum of this list of digits must be S.

```
> 8 votes

# Answer
# 05AB1E, ~~11~~ 17 bytes

```
X›0si¹ÒSO¹SOQ¹p_&

```

**Explanation**

```
X›0si              # if input is less than 2 then false, else
       SO          # sum of digits
     ¹Ò            # of prime factors with duplicates
            Q      # equal to
          SO       # sum of digits
         ¹         # of input
                &  # and
             ¹p_   # input is not prime

```

Try it online!
> 7 votes

# Answer
## PowerShell v3+, 183 bytes

```
param($n)$b=@();for($a=$n;$a-gt1){2..$a|?{'1'*$_-match'^(?!(..+)\1+$)..'-and!($a%$_)}|%{$b+=$_;$a/=$_}}$n-notin$b-and(([char[]]"$n")-join'+'|iex)-eq(($b|%{[char[]]"$_"})-join'+'|iex)

```

No built-in prime checking. No built-in factoring. No built-in digit-sum. Everything's hand made. :D

Takes input `$n` as an integer, sets `$b` equal to an empty array. Here, `$b` is our collection of prime factors.

Next is a `for` loop. We first set `$a` equal to our input number, and the conditional is until `$a` is less-than-or-equal-to 1. This loop is going to find our prime factors.

We loop from `2` up to `$a`, uses `Where-Object` (`|?{...}`) to pull out primes that are also factors `!($a%$_)`. Those are fed into an inner-loop `|%{...}` that places the factor into `$b` and divides `$a` (thus we'll eventually get to `1`).

So, now we have all of our prime factors in `$b`. Time to formulate our Boolean output. We need to verify that `$n` is `-notin` `$b`, because if it is that means that `$n` is prime, and so isn't a Smith number. Additionally, (`-and`) we need to make sure that our two sets of digit sums are `-eq`ual. The resulting Boolean is left on the pipeline and output is implicit.

**NB** \- Requires v3 or newer for the `-notin` operator. ~~I'm still running the input for `4937775` (this is *slow* to calculate), so I'll update this when that finishes.~~ After 3+ hours, I got a stackoverflow error. So, there's some upper-bound somewhere. Oh well.

This will work for negative input, zero, or one, because the right-hand of the `-and` will barf out an error while it tries to calculate the digit sums (shown below), which will cause that half to go to `$false` when evaluated. Since STDERR is ignored by default, and the correct output is still displayed, this is fine.

---

### Test cases

```
PS C:\Tools\Scripts\golfing> 4,22,27,58,85,94,18,13,666,-265,0,1|%{"$_ -> "+(.\is-this-a-smith-number.ps1 $_)}
4 -> True
22 -> True
27 -> True
58 -> True
85 -> True
94 -> True
18 -> False
13 -> False
666 -> True
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

-265 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

0 -> False
Invoke-Expression : Cannot bind argument to parameter 'Command' because it is an empty string.
At C:\Tools\Scripts\golfing\is-this-a-smith-number.ps1:1 char:179
+ ... "$_"})-join'+'|iex)
+                    ~~~
    + CategoryInfo          : InvalidData: (:String) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand

1 -> False

```
> 5 votes

# Answer
# MATL, 17 bytes

```
YftV!UsGV!Us=wnqh

```

Outputs truthy or falsey arrays where a truthy output requires that *all* elements be non-zero.

**Try it online**
> 3 votes

# Answer
# Jelly, ~~27 25~~ 23 bytes

(further golfing ~~probably~~ definitely possible)

```
ḢDS×
ÆFÇ€SḢ
DS=Ça<2oÆP¬

```

Returns `0` for False or `1` for True

All test cases at **TryItOnline**

How?

```
DS=Ça<2oÆP¬ - main link takes an argument, n
DS          - transform n to a decimal list and sum up
   Ç        - call the previous link (ÆFÇ€SḢ)
  =         - test for equality
     <2     - less than 2?
    a       - logical and
        ÆP  - is prime?
       o    - logical or
          ¬ - not
            - all in all tests if the result of the previous link is equal to the digit
              sum if the number is composite otherwise returns 0.

ÆFÇ€SḢ - link takes an argument, n again
ÆF     - list of list of n's prime factors and their multiplicities
  Ç€   - apply the previous link (ḢDS×) for each
    S  - sum up
     Ḣ - pop head of list (there will only be one item)

ḢDS× - link takes an argument, a factor, multiplicity pair
Ḣ    - pop head, the prime factor - modifies list leaving the multiplicity
 DS  - transform n to a decimal list and sum up
   × - multiply the sum with the multiplicity

```
> 3 votes

# Answer
# Actually, 18 bytes

Unfortunately, Actually doesn't have a factorization builtin that gives a number's prime factors to multiplicity, so I had to hack one together. Golfing suggestions welcome. Try it online!

```
;w`i$n`MΣ♂≈Σ@$♂≈Σ=

```

**Ungolfing**

```
         Implicit input n.
;w       Duplicate n and get the prime factorization of a copy of n.
`...`M   Map the following function over the [prime, exponent] lists of w.
  i        Flatten the list. Stack: prime, exponent.
  $n       Push str(prime) to the stack, exponent times.
            The purpose of this function is to get w's prime factors to multiplicity.
Σ        sum() the result of the map.
          On a list of strings, this has the same effect as "".join()
♂≈Σ      Convert every digit to an int and sum().
@        Swap the top two elements, bringing other copy of n to TOS.
$♂≈Σ     Push str(n), convert every digit to an int, and sum().
=        Check if the sum() of n's digits is equal
          to the sum of the sum of the digits of n's prime factors to multiplicity.
         Implicit return.

```
> 3 votes

# Answer
# Octave, ~~80~~ 78 bytes

```
t=num2str(factor(x=input('')))-48;disp(any(t<0)&~sum([num2str(x)-48 -t(t>0)]))

```

Explanation:

```
factor(x=input(''))                 % Take input, store as x and factor it
num2str(factor(x=input('')))-48     % Convert it to an array (123 -> [1 2 3])
                                    % and store as t
any(t<0)                            % Check if there are several prime factors
                                    % [2 3] -> [2 -16 3]
sum([num2str(x)-48 -t(t>0)])        % Check if sum of prime factor
                                    % is equal the sum of digits

```

Try it online.
> 2 votes

# Answer
# Haskell, ~~120~~ 105 bytes

```
1%_=[];a%x|mod a x<1=x:div a x%x|0<1=a%(x+1)
p z=sum[read[c]|c<-show z]
s x|z<-x%2=z<[x]&&sum(p<$>z)==p x

```
> 2 votes

# Answer
# JavaScript (ES6),  ~~87 86~~  84 bytes

```
m=>(i=2,S=0,g=n=>([...i+''].map(v=>s-=v,s=S),i-m?n%i?g(n,i++):g(n/i,S=s):s==2*S))(m)

```

Try it online!
> 2 votes

# Answer
# Pyth, 21 bytes

```
&&>Q1!P_QqsjQTssmjdTP

```

A program that takes input of an integer and prints `True` or `False` as relevant.

Try it online

**How it works**

```
&&>Q1!P_QqsjQTssmjdTP  Program. Input: Q
           jQT         Yield digits of the base-10 representation of Q as a list
          s            Add the digits
                    P  Yield prime factors of Q (implicit input fill)
                mjdT   Map base-10 representation across the above, yielding digits of each
                       factor as a list of lists
               s       Flatten the above
              s        Add up the digits
         q             Those two sums are equal
&                      and
  >Q1                  Q>1
 &                     and
     !P_Q              Q is not prime
                       Implicitly print

```
> 2 votes

# Answer
# Perl 6, ~~92~~ ~~88~~ 87 bytes

~~```
{sub f(\i){my \n=first i%%*,2..i-1;n??n~f i/n!!i}
!.is-prime&&$_>1&&.comb.sum==.&f.comb.sum}

```~~
```
{sub f(\i){my \n=first i%%*,2..^i;n??[n,|f i/n]!!|i}
$_>.&f>1&&.comb.sum==.&f.comb.sum}

```

An anonymous function that returns a Bool.

* Now does 100% manual factorization and primality checking.
* Saved some bytes by testing both "input \> 1" and "number of factors \> 1" with one chained comparison, since m \> Ω(m).

(try it online)

*EDIT: -1 byte thanks to b2gills*
> 2 votes

# Answer
# Brachylog (newer), 11 bytes

```
¬ṗ&ẹ+.&ḋcẹ+

```

Try it online!

Predicate succeeds if the input is a Smith number and fails if it is not.

```
               The input
¬ṗ             is not prime,
  &            and the input's
   ẹ           digits
    +          sum to
     .         the output variable,
      &        and the input's
       ḋ       prime factors' (getting prime factors of a number < 1 fails)
        c      concatenated
         ẹ     digits
          +    sum to
               the output variable.

```
> 2 votes

# Answer
# Japt, ~~14~~ 11 bytes

```
ìx ¥Uk x_ìx

```

*-3 bytes thanks to @Shaggy*

Try it online!
> 2 votes

# Answer
# APL (Dyalog Extended), ~~36~~ 29 bytesSBCS

This answer owes its golfiness to Extended's  monad for returning the prime factors of a number, and that  is better at base-conversion than in Dyalog Unicode.

Edit: -7 bytes thanks to dzaima.

```
{2>⍵:0⋄(⊃=+/-⊃×2<≢)+⌿10⊤⍵,⍭⍵}

```

Try it online!

**Explanation**

```
{1⋄(3)2}  A dfn, a function in brackets. ⋄ is a statement separator.
          The numbers signify the sections in the order they are explained.

2>⍵:0  If we have a number less than 2,
       we immediately return 0 to avoid a DOMAIN ERROR.

+⌿10⊤⍵,⍭⍵
        ⍭⍵  We take the factors of ⍵, our input as our right argument,
      ⍵,    and append it to our input again.
   10⊤      before converting the input and its factors into a matrix of their base-10 digits
            (each row is the places, units, tens, hundreds, etc.)
+⌿         And taking their sum across the columns of the resulting matrix,
            to give us the sum of their digits, their digit-sums.

(⊃=+/-⊃×2<≢)  We run this section over the list of sums of digits above.
 ⊃=+/-⊃       We check if the main digit-sum (of our input)
               Is equal to the sum of our digit-sums
               (minus our main digit-sum that is also still in the list)
        ×2<≢   The trick here is that we can sneak in our composite check
               (if our input is prime there will be only two numbers,
               the digit-sum of the prime,
               and the digit-sum of its sole prime factor, itself)
               So if we have a prime, we zero our (minus our main sum)
               in the calculation above, so that primes will not succeed in the check.
               We return the result of the check.

```
> 2 votes

# Answer
# Rutger, 504 bytes

```
x=$Input;
t=Not[IsPrime[$x]];
c=();
d=p=0;
i=IfElse[{l=LessThan[$x];l[1]}];
i=i[{t=0;}];
i=i[{s=Array[Str[$x]];e=Each[$s];e=e[@i];e=e[{a=Add[$d];d=a[Integer[$i]];}];Do[$e];r=2;w=While[{Decrement[$x];}];w=w[{i=IfElse[{m=Modulo[$x];Not[m[$r]];}];i=i[{a=Append[$c];v=Divide[$x];x=Integer[v[$r]];c=a[Array[Str[$r]]];}];i=i[{r=Increment[$r];}];Do[$i];}];Do[$w];h=Each[$c];h=h[@k];h=h[{l=Each[$k];l=l[@n];l=l[{a=Add[$p];p=a[Integer[$n]];}];Do[$l];}];Do[$h];}];
Do[$i];
z=Times[$t];
e=Equal[$d];
Print[z[e[$p]];

```

Try it online!

Rutger isn't a particularly short language, and doesn't excel at having to split an integer into its constituent digits.
> 2 votes

# Answer
# APL (Dyalog Extended), 26 bytes

```
(×/≡⍥(+/⍣≡10⊤⊢)⊢×1<≢)⍭⍤⌈∘2

```

Try it online!

A golfed version of Sherlock9's solution. A nice use case for Over `f⍥g`, which performs `g` on both sides and combines the two with `f`.

### How it works

```
(×/≡⍥(+/⍣≡10⊤⊢)⊢×1<≢)⍭⍤⌈∘2  ⍝ Input: n
                       ⌈∘2  ⍝ max(n,2)
                     ⍭⍤     ⍝ Prime factorization of above
(              ⊢×1<≢)       ⍝ Side 1: if n is not composite, multiply ^ with zero
 ×/                         ⍝ Side 2: multiply all primes to get original number
    ⍥(        )  ⍝ Operate on each side..
          10⊤⊢   ⍝ Base-10 digits of each number
      +/⍣≡       ⍝ Sum all of them
   ≡             ⍝ Check equality of the two sides

```
> 2 votes

# Answer
# tinylisp, 131 bytes

```
(load library
(d F(q((X)(*(*(not(prime? X))X)(e(sum(to-base 10 X))(sum(map(q((X)(s X 48)))(chars(join(map string(prime-factors X))(

```

Try it online!

An unintentional golf at `join` which through some weird behaviour ends up producing the right thing. Rest of it is just the formula given in the question.
> 2 votes

# Answer
# Vyxal, 63 bitsv2, 7.875 bytes

```
₍‡ǐvffṠṠ≈

```

Try it Online!

Bitstring:

```
110001111001001111101010000010100001001101010011001110100101010

```

```
₍‡ǐvffṠṠ≈
₍          # Wrap the next to items in a list
 ‡ǐvf      # list of digits for each prime factor
     f     # list of digits of original number
      ṠṠ   # vectorised sum twice (quirk of list depth from digit lists)
        ≈  # are they equal

```

Created with the help of Luminespire.
> 2 votes

# Answer
## Pyke, 16 bytes

```
Pm[`mbs(sQ[qRlt*

```

Try it here!
> 1 votes

# Answer
# Java 7, ~~509~~ ~~506~~ ~~435~~ ~~426~~ ~~419~~ 230 bytes

```
boolean c(int n){return n<2|p(n)?0>1:d(n)==f(n);}int d(int n){return n>9?n%10+d(n/10):n;}int f(int n){int r=0,i;for(i=1;++i<=n;)for(;n%i<1;n/=i,r+=i>9?d(i):i);return r;}boolean p(int n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}

```

I should have listened to *@BasicallyAlanTuring*'s comment..

> This is one of those questions where I thought "Java+this=no", I upvoted for the idea though :P

Ah well.. Some programming languages use a single byte for the prime-factors or prime-check, but Java is certainly not one of them.

EDIT: Halved the amount of bytes now that I had some time to think about it.

**Ungolfed (sort-off..) & test cases:**

Try it here.

```
class M{
  static boolean c(int n){
    return n < 2 | p(n)
            ? 0 > 1 //false
            : d(n) == f(n);
  }

  // Sums digits of int
  static int d(int n) {
    return n > 9
            ? n%10 + d(n/10)
            : n;
  }

  // Convert int to sum of prime-factors
  static int f(int n) {
    int r = 0,
        i;
    for(i = 1; ++i <= n; ){
      for( ; n % i < 1; n /= i,
                        r += i > 9 ? d(i) : i);
    }
    return r;
  }

  // Checks if the int is a prime
  static boolean p(int n){
    int i = 2;
    while(i < n){
      n = n % i++ < 1
           ? 0
           : n;
    }
    return n > 1;
  }

  public static void main(String[] a){
    System.out.println(c(18));
    System.out.println(c(22));
    System.out.println(c(13));
    System.out.println(c(666));
    System.out.println(c(-256));
    System.out.println(c(0));
    System.out.println(c(1));
    System.out.println(c(4937775));
  }
}

```

**Output:**

```
false
true
false
true
false
false
false
true

```
> 1 votes

# Answer
# , ~~31~~ 30 bytes

```
0&p:*](=+/)&(1#."."0@":)q: ::1

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~139~~ 136 bytes

```
S(m,i,t,h,_){t=m=m<2?2:m;for(_=h=i=1;m>1;h=1){while(m%++h);for(m/=h;i+=h%10,h/=10;);}while(t%++h);for(m=t;_+=m%10,m/=10;);m=t-h?i==_:0;}

```

Try it online!

-3 bytes thanks to ceilingcat

Explanation:

```
/*
 * Variable mappings:
 *  is_smith      => S
 *  argument      => m
 *  factor_digits => i
 *  arg_copy      => t
 *  least_factor  => h
 *  digit_sum     => _
 */
int is_smith(int argument){                     /* S(m,i,t,h,_){ */
    int factor_digits;
    int arg_copy;
    int least_factor;
    int digit_sum;

    /*
     * The cases of 0 and 1 are degenerate.
     * Mapping them to a non-degenerate case with the right result.
     */
    if (argument < 2) {                         /* t=m=m<2?2:m; */
        argument = 2;
    }
    arg_copy = argument;

    /*
     * Initializing these to 1 instead of zero is done for golf reasons.
     * In the end we just compare them, so it doesn't really matter.
     */
    factor_digits = 1;                          /* for(_=h=i=1; */
    digit_sum = 1;

    /* Loop over each prime factor of argument */
    while (argument > 1) {                      /* m>1; */

        /*
         * Find the smallest factor
         * Note that it is initialized to 1 in the golfed version since prefix
         * increment is used in the modulus operation.
         */
        least_factor = 2;                       /* h=1){ */
        while (argument % least_factor != 0)    /* while(m% */
            least_factor++;                     /* ++h); */
        argument /= least_factor;               /* for(m/=h; */

        /* Add its digit sum to factor_digits */
        while (least_factor > 0) {
            factor_digits += least_factor % 10; /* i+=h%10, */
            least_factor /= 10;                 /* h/=10;) */
        }                                       /* ; */

    }                                           /* } */

    /* In the golfed version we get this for free in the for loop. */
    least_factor = 2;
    while (arg_copy % least_factor != 0)        /* while(t% */
        least_factor++;                         /* ++h); */

    /* Restore the argument */
    argument = arg_copy;                        /* for(m=t; */

    /* Compute the arguments digit sum */
    while (argument > 0) {
        digit_sum += argument % 10;             /* _+=m%10, */
        argument /= 10;                         /* m/=10;) */
    }                                           /* ; */

    /* This return is done by assigning to first argument when golfed. */
                                                /* m= */
    if (arg_copy == least_factor) {             /* t==h? */
        return 0; /* prime input */             /* 0 */
    } else {                                    /* : */
        return digit_sum == factor_digits;      /* i == _ */
    }                                           /* ; */
}                                               /* } */

```
> 1 votes

# Answer
# Racket 176 bytes

```
(define(sd x)(if(= x 0)0(+(modulo x 10)(sd(/(- x(modulo x 10))10)))))
(require math)(define(f N)
(if(=(for/sum((i(factorize N)))(*(sd(list-ref i 0))(list-ref i 1)))(sd N))1 0))

```

Returns 1 if true and 0 if false:

```
(f 27)
1
(f 28)
0
(f 85)
1
(f 86)
0

```

Detailed version:

```
(define (sd x)   ; fn to find sum of digits
  (if (= x 0)
      0
      (+ (modulo x 10)
         (sd (/ (- x (modulo x 10)) 10)))))

(require math)
(define (f N)
  (if (= (for/sum ((i (factorize N)))
           (* (sd (list-ref i 0))
              (list-ref i 1)))
         (sd N)) 1 0))

```
> 0 votes

# Answer
# Rust - 143 bytes

```
fn t(mut n:u32)->bool{let s=|k:u32| (2..=k).fold((0,k),|(a,m),_|(a+m%10,m/10));s(n).0==(2..n).fold(0,|mut a,d|{while n%d<1{n/=d;a+=s(d).0};a})}

```

borrowed python solution by @levitatinglion ... at least this is shorter than Java...

degolfed at play.rust-lang.org
> 0 votes

# Answer
# APL(NARS), 39 chars, 78 bytes

```
{⍵≤0:0⋄0π⍵:0⋄(2×↑a)=+/a←+/¨{⍎¨⍕⍵}¨⍵,π⍵}

```

test:

```
  f←{⍵≤0:0⋄0π⍵:0⋄(2×↑a)=+/a←+/¨{⍎¨⍕⍵}¨⍵,π⍵}
  f¨0..10
0 0 0 0 1 0 0 0 0 0 0
  ⎕fmt {⍵,f⍵}¨18,22,13,666,¯265,0,1,4937775
┌8────────────────────────────────────────────────────────────────────┐
│┌2────┐ ┌2────┐ ┌2────┐ ┌2─────┐ ┌2──────┐ ┌2───┐ ┌2───┐ ┌2─────────┐│
││ 18 0│ │ 22 1│ │ 13 0│ │ 666 1│ │ ¯265 0│ │ 0 0│ │ 1 0│ │ 4937775 1││
│└~────┘ └~────┘ └~────┘ └~─────┘ └~──────┘ └~───┘ └~───┘ └~─────────┘2
└∊────────────────────────────────────────────────────────────────────┘

```
> 0 votes

# Answer
# C (gcc), 177 Bytes

Defines a function `Q` that returns 0 for smith numbers and nonzero for non-smith numbers

```
#define r return
O(D,i){for(i=0;D>0;i+=D%10,D-=D%10,D/=10);r i;}D(O,o){for(o=1;o<O;)if(O%++o<1)r o;r O;}Q(p,q,i,j){if(p^(q=D(i=p))){for(j=0;p>1;q=D(p/=q))j+=O(q);r j^O(i);}r 1;}

```

Try it online!

Explanation:

```
// Return the sum of digits of D if D > 0, otherwise 0
O(D,i){
    // While D is greater than 0:
    // Add the last digit of D to i, and remove the last digit from D
    for(i=0;D>0;i+=D%10,D-=D%10,D/=10);
    return i;
}
// Return the smallest prime factor of O if O>1 else O
D(O,o){
    // Iterate over numbers less than O
    for(o=1;o<O;)
        // If O is divisible by o return o
        if(O%++o<1)
            return o;
    // Otherwise return O
    return O;
}
Q(p,q,i,j){
    // Set q to D(p) and i to p
    // If p != D(p) (i.e, p is composite and > 0)
    if(p^(q=D(i=p))){
        // Iterate over the prime factors of p and store their digit sum in j
        for(j=0;p>1;q=D(p/=q))
            j+=O(q);
        // i is the original value of p. If O(i)^j == 0, O(i) == j
        return j^O(i);
    }
    // If p was composite or < 0, return 1
    return 1;
}

```
> 0 votes

# Answer
## C# (Visual C# Interactive Compiler), 122 bytes

```
n=>{int m=n,b=0,a=$"{n}".Sum(x=>x-'0');for(int i=2;i<m;i++)if(n%i==0){b+=$"{i}".Sum(x=>x-'0');n/=i;i=1;}return n>0&&a==b;}

```

Try it online!
> 0 votes

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