title: Calculate ISBN-13 check digit

text:
# Question
Title: Calculate ISBN-13 check digit
Write a function which, given the first 12 digits of an ISBN-13 code, will calculate the entire ISBN via calculating and appending an appropriate check digit.

Your function's input is a string containing the first 12 digits of the ISBN. Its output is a string containing all 13 digits.

## Formal specification

Write a function which, when given a string *s* consisting entirely of exactly 12 decimal digits (and no other characters), returns a string *t* with the following properties:

* *t* consists of exactly 13 decimal digits (and no other characters);
* *s* is a prefix of *t*;
* the sum of all digits in odd positions in *t* (i.e. the first, third, fifth, etc.), plus three times the sum of all digits in even positions in *t* (i.e. the second, fourth, sixth, etc), is a multiple of 10.

## Example / test case

**Input**
`978030640615`

**Output**
`9780306406157`

## Victory condition

As a challenge, the shortest answer wins.

# Answer
> 15 votes
## Golfscript - 25 chars

```
{...+(;2%+{+}*3-~10%`+}:f

```

Whole program version is only 19 chars

```
...+(;2%+{+}*3-~10%

```

Check back here for analysis later. Meanwhile check out my old uninspired answer

**Golfscript - 32 chars**

Similar to the luhn number calculation

```
{.{2+}%.(;2%{.+}%+{+}*~)10%`+}:f

```

Analysis for 978030640615

```
{...}:f this is how you define the function in golfscript
.       store an extra copy of the input string
        '978030640615' '978030640615'
{2+}%   add 2 to each ascii digit, so '0'=>50, I can get away with this instead
        of {15&}% because we are doing mod 10 math on it later
        '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55]
.       duplicate that list
        '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [59 57 58 50 53 50 56 54 50 56 51 55]
(;      trim the first element off
        '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [57 58 50 53 50 56 54 50 56 51 55]
2%      select every second element
        '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [57 50 50 54 56 55]
{.+}%   double each element by adding to itself
        '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55] [114 100 100 108 112 110]
+       join the two lists together
        '978030640615' [59 57 58 50 53 50 56 54 50 56 51 55 114 100 100 108 112 110]
{+}*    add up the items in the list
        '978030640615' 1293
~       bitwise not
        '978030640615' -1294
)       add one
        '978030640615' -1293
10%     mod 10
        '978030640615' 7
`       convert to str
        '978030640615' '7'
+       join the strings
        '9780306406157'

```

# Answer
> 10 votes
## Python - 44 chars

```
f=lambda s:s+`-sum(map(int,s+s[1::2]*2))%10`

```

Python - 53 chars

```
def f(s):d=map(int,s);return s+`-sum(d+d[1::2]*2)%10`

```

# Answer
> 7 votes
## Haskell - 54 characters

```
i s=s++show(sum[-read[c]*m|c<-s|m<-cycle[1,3]]`mod`10)

```

This requires support for parallel list comprehensions, which is supported by GHC (with the `-XParallelListComp` flag) and Hugs (with the `-98` flag).

# Answer
> 7 votes
## APL (27 characters)

```
F←{⍵,⍕10|10-(12⍴1 3)+.×⍎¨⍵}

```

I'm using Dyalog APL as my interpreter. Here's a quick explanation, mostly from right to left (within the function definition, `F←{ ... }`):

* `⍎¨⍵`: Execute/evaluate () each (`¨`) character given in the right argument ().
* `(12⍴1 3)`: Reshape () the vector `1 3` into a `12`-element vector (repeating to fill the gaps).
* `+.×`: Take the dot product (`+.×`) of its left argument (`(12⍴1 3)`) and its right argument (`⍎¨⍵`).
* `10-`: Subtract from 10.
* `10|`: Find the remainder after division by `10`.
* : Format the number (i.e., give a character representation).
* `⍵,`: Append (`,`) our calculated digit to the right argument.

# Answer
> 6 votes
## PHP - ~~86~~ ~~85~~ 82 chars

```
function c($i){for($a=$s=0;$a<12;)$s+=$i[$a]*($a++%2?3:1);return$i.(10-$s%10)%10;}

```

Re-format and explanation:

```
function c($i){                     // function c, $i is the input

    for($a=$s=0;$a<12;)             // for loop x12 - both $a and $s equal 0
                                    // notice there is no incrementation and
                                    // no curly braces as there is just one
                                    // command to loop through

        $s+=$i[$a]*($a++%2?3:1);    // $s (sum) is being incremented by
                                    // $ath character of $i (auto-casted to
                                    // int) multiplied by 3 or 1, depending
                                    // wheter $a is even or not (%2 results
                                    // either 1 or 0, but 0 == FALSE)
                                    // $a is incremented here, using the
                                    // post-incrementation - which means that
                                    // it is incremented, but AFTER the value
                                    // is returned

    return$i.(10-$s%10)%10;         // returns $i with the check digit
                                    // attached - first it is %'d by 10,
                                    // then the result is subtracted from
                                    // 10 and finally %'d by 10 again (which
                                    // effectively just replaces 10 with 0)
                                    // % has higher priority than -, so there
                                    // are no parentheses around $s%10
}

```

# Answer
> 6 votes
## Windows PowerShell, 57

```
filter i{$_+(990-($_-replace'(.)(.)','+$1+3*$2'|iex))%10}

```

# Answer
> 5 votes
## Haskell, ~~78~~ ~~71~~ 66 characters

```
i s=s++(show$mod(2-sum(zipWith(*)(cycle[1,3])(map fromEnum s)))10)

```

# Answer
> 5 votes
## Ruby - ~~73~~ 65 chars

```
f=->s{s+((2-(s+s.gsub(/.(.)/,'\1')*2).bytes.inject(:+))%10).to_s}

```

# Answer
> 4 votes
**Python - ~~91~~, 89**

```
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
|         |         |         |         |         |         |         |         |         |
 def c(i):return i+`(10-(sum(int(x)*3for x in i[1::2])+sum(int(x)for x in i[::2]))%10)%10`

```

# Answer
> 4 votes
**C# (94 characters)**

```
string I(string i){int s=0,j=0;for(;j<12;)s+=(i[j]-48)*(j++%2<1?1:3);return i+((10-s%10)%10);}

```

With linebreaks/whitespace for readability:

```
string I(string i)
{
    int s = 0, j = 0;
    for (; j < 12; )
        s += (i[j] - 48) * (j++ % 2 < 1 ? 1 : 3);
    return i + ((10 - s % 10) % 10);
}

```

Tested on several ISBNs from books on my shelf, so I know it's working!

# Answer
> 4 votes
## J - 55 45 38

```
f=:3 :'y,":10|10-10|+/(12$1 3)*"."0 y'

```

eg

```
f '978030640615'
9780306406157

```

old way:

```
f=:,":@(10(10&|@-)(10&|@+/@((12$1 3)*(i.12)&(".@{))))

```

# Answer
> 4 votes
## C# – ~~89~~ 77 characters

```
string I(string s){return s+(9992-s.Sum(x=>x-0)-2*s.Where((x,i)=>i%2>0).Sum(x=>x-0))%10;}

```

Formatted for readability:

```
string I(string s)
{
    return s +
            (9992
            - s.Sum(x => x - 0)
            - 2 * s.Where((x, i) => i%2 > 0).Sum(x => x - 0)
            ) % 10;
}

```

We do not multiply by one or three, we just add everything, plus we add all even-placed characters one more time, multiplied by two.

9992 is large enough so that the sum of all ASCII characters is less than that (so that we may mod by 10 and be sure the result is positive, no need to mod by 10 twice), and is not divisible by zero because we add up all those extra 2\*12\*48 (twelve ASCII digits, weighed by 1 and 3) == 1152, which allows us to spare one extra character (instead of twice subtracting 48, we subtract 0 just to convert from char to int, but instead of 990, we need to write 9992).

But then again, even though much less beautiful ;-), this old-school solution gets us to 80 characters (but this is almost C-compatible):

```
string T(string i){int s=2,j=0;for(;j<12;)s+=i[j]*(9-j++%2*2);return i+s%10;}

```

# Answer
> 4 votes
# Perl 6, ~~29~~ 28 bytes

```
{$_~:1[.comb «*»(9,7)]%10}

```

Try it online!

# Answer
> 3 votes
## Ruby - 80 characters

```
def f s;s+(10-s.bytes.zip([1,3]*6).map{|j,k|(j-48)*k}.inject(:+)%10).to_s[0];end

```

# Answer
> 3 votes
## Perl, 53 chars

```
sub i{($_)=@_;s/(.)(.)/$s+=$1+$2*3/ger;$_.(10-$s)%10}

```

# Answer
> 3 votes
## dc, 44 chars

```
[d0r[I~3*rI~rsn++lndZ0<x]dsxx+I%Ir-I%rI*+]sI

```

Invoke as `lIx`, e.g:

```
dc -e'[d0r[I~3*rI~rsn++lndZ0<x]dsxx+I%Ir-I%rI*+]sI' -e '978030640615lIxp'

```

# Answer
> 3 votes
# Q, 36 chars

```
{x,-3!10-mod[;10]sum(12#1 3)*"I"$'x}

```

# Answer
> 2 votes
**D - 97 characters**

```
auto f(string s){int n;foreach(i,c;s)n+=((i&1)*2+1)*(c-48);return s~cast(char)((10-n%10)%10+48);}

```

Formatted more legibly:

```
auto f(string s)
{
    int n;

    foreach(i, c; s)
        n += ((i & 1) * 2 + 1) * (c - 48);

    return s ~ cast(char)((10 - n % 10) % 10 + 48);
}

```

The verbosity of D's cast operator definitely makes it harder to write obsessively short code though.

# Answer
> 2 votes
**Java - 161 Characters** :(

```
int b[]=new int[a.length];
int d=0,n=0,j=1;
for(char c:a.toCharArray())b[d++]=Integer.valueOf(c+"");
for(int i:b)n+=(j++%2==0)?(i*3):(i*1);
return a+(10-(n%10));

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 18 bytesSBCS

Anonymous tacit prefix function taking string as argument. Using Bubbler's approach.

```
⊢,∘⍕10|⍎¨+.×9 7⍴⍨≢

```

Try it online!

length of argument (12)

`9 7⍴⍨` cyclically reshape `[9,7]` to that length

`+.×` dot product of the following with that:

`⍎¨` \`evaluate each character

`10|` mod-10 of that

`,∘⍕` prepend the following the the stringification of that:

the unmodified argument

# Answer
> 2 votes
# 05AB1E, 11 bytes

```
SιO`3*+θTα«

```

Try it online or verify a few more test cases.

**Explanation:**

```
S            # Convert the (implicit) input to a list of digits
             #  i.e. 978030640615 → [9,7,8,0,3,0,6,4,0,6,1,5]
 ι           # Uninterleave it
             #  → [[9,8,3,6,0,1],[7,0,0,4,6,5]]
  O          # Sum each inner list
             #  → [27,22]
   `         # Push them both separated to the stack
    3*       # Multiply the top one by 3
             #  → 66
      +      # Sum them together
             #  → 93
       θ     # Only leave the last digit
             #  → 3
        Tα   # Take the absolute difference of this digit with 10
             #  → 7
          «  # And append this digit to the (implicit) input
             #  → 9780306406157
             # (after which it is output implicitly as result)

```

# Answer
> 2 votes
# Vyxal, 8 bytes

```
⁽Tẇ∑N₀%J

```

Try it Online!

Port of Jelly

## Explained

```
⁽Tẇ∑N₀%J
⁽Tẇ       # Triple every second digit
   ∑N     # -sum of that
     ₀%   # modulo by 10
       J  # append that result to the original input

```

# Answer
> 1 votes
# Q (44 chars)

```
f:{x,string 10-mod[;10]0+/sum@'2 cut"I"$/:x}

```

# Answer
> 1 votes
## Scala 84

```
def b(i:String)=i+(10-((i.sliding(2,2).map(_.toInt).map(k=>k/10+k%10*3).sum)%10)%10)

```

Testing:

```
val isbn="978030640615"
b(isbn)

```

Result:

```
"9780306406157"

```

# Answer
> 1 votes
# C, 80 79 characters

The function modifies the string in place, but returns the original string pointer to satisfy the problem requirements.

```
s;char*f(char*p){for(s=2;*p;s+=7**p++)s+=9**p++;*p++=48+s%10;*p=0;return p-13;}

```

Some explanation: Instead of subtracting 48 (the ASCII value of the digit `0`) from each input character, the accumulator `s` is initialized so that it is modulo 10 equal to 48+3\*48+48+3\*48...+48+3\*48 = 24\*48 = 1152. The step `10-sum` can be avoided by accumulating `s` by subtraction instead of addition. However, the module operator `%` in C would not give a usable result if `s` was negative, so instead of using `s-=` the multipliers 3 and 1 are replaced by -3=7 modulo 10 and -1=9 modulo 10, respectively.

Test harness:

```
#include <stdio.h>
#define N 12
int main()
{
     char b[N+2];
     fgets(b, N+1, stdin);
     puts(f(b));
     return 0;
}

```

# Answer
> 1 votes
# Groovy 75, 66 chars

```
i={int i;it+(10-it.inject(0){t,c->t+(i++&1?:3)*(c as int)}%10)%10}

```

use:

```
String z = "978030640615"
println i(z)

-> 9780306406157

```

# Answer
> 1 votes
### APL (25)

```
{⍵,⍕10-10|+/(⍎¨⍵)×12⍴1,3}

```

# Answer
> 1 votes
# Python 2, ~~78~~ 76 bytes

```
lambda n:n+`10-(sum(int(a)+3*int(b)for a,b in zip(n[::2],n[1::2]))%10or 10)`

```

Try it online!

Takes a string as an argument.

# Explanation:

Using python slice notation, converts a string into a list of character pairs. ("978030640615" -\> \[("9","7"), ("8", "0"), ("3", "0"), ("6", "4"), ("0", "6"), ("1", "5")\] )

For that list of pairs, converts each item into an integer and returns a+3b.

Sums all the results.

Gets the sum modulo 10, OR 10 if the remainder is 0. (This prevents the final digit from being 10 instead of 0.)

Removes the remainder from 10 to get the check digit.

Converts the calculated check digit to a string via deprecated backtick expression.

Returns the original number plus the calculated check digit.

# Edit:

Saved 2 byes by removing spaces (thanks Jo King!).

# Answer
> 1 votes
# Stax, ~~11~~ 10 bytes

```
╣Γ♠☼ù≤m╒X₧

```

Run and debug it

This is a complete program instead of a function, as stax does not implement functions.

Unpacked, ungolfed, and commented, it looks like this.

```
q   print input without popping and without newline
E   explode into array of decimal digits
97E [9,7] (this will become the repetition counts)
:B  repeat elements; repetition counts wrap around to cover all input digits
|+  get sum of array with repeated digts
A%  modulus 10
P   print

```

Run this one

# Answer
> 1 votes
# Powershell, ~~55~~ ~~53~~ 52 bytes

*Inspired by Joey's answer. I'm impressed with her regex.*

```
"$args"+($args-replace'(.)(.)','+40-$1-3*$2'|iex)%10

```

## Powershell, 55 bytes, whithout regex

```
param($s)$s[1,3,5,7,9,11*2+0..11]|%{$r+=58-$_};$s+$r%10

```

Explanation:

* the index range = (the even positions `1,3,5,7,9,11` repeated 2 times + all positions `0..11`)
* `$r+=58-$_` makes a sum of supplements up to `10+[char]'0'`
* `$s+$r%10` outputs the result

Test script:

```
$f = {

param($s)$s[1,3,5,7,9,11*2+0..11]|%{$r+=58-$_};$s+$r%10

}

@(
    ,("978030640615" , "9780306406157")

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected)"
    $s
    $result
}

```

Output:

```
True
978030640615
9780306406157

```

# Answer
> 1 votes
# APL(NARS), chars 38, bytes 76

```
{⍵,10∣10-10∣+/w,2×w[v/⍨∼2∣v←⍳≢w←⍎¨⍕⍵]}

```

I had some other test for see better and get definition from Wikipedia, and examples in the page: https://isbn-information.com/check-digit-for-the-13-digit-isbn.html test:

```
  h←{⍵,10∣10-10∣+/w,2×w[v/⍨∼2∣v←⍳≢w←⍎¨⍕⍵]}
  h 978186197271
978186197271 2
  h 978168197271
978168197271 8
  h 978186197371
978186197371 9
  h 978186197375
978186197375 7

```

the formula i use would be in one not APL language if w is the argument =\>

```
f(w)==w,(10-(sum(digit(w),2*digitsEVENINDICES(w))mod 10))mod 10

```

comment:

```
{⍵,10∣10-10∣+/w,2×w[v/⍨∼2∣v←⍳≢w←⍎¨⍕⍵]}
                   v/⍨∼2∣v←⍳≢w←⍎¨⍕⍵] call w the array of digits of ⍵, return even index
               2×w[                  consider all the digit even of w and multipy for 2
             w,                      put above that array, the array w
           +/                        sum all
      10-10∣                          10 - (above sum)mod 10
    10∣                               above mod 10
 {⍵,                                 add as digit to the number of argument, and return all that

```

# Answer
> 1 votes
# dc, 25 bytes

```
dn[A~9z^8+*rd0<M+]dsMxA%p

```

Try it online!

I know there's already a dc answer here, but 25\<44 so I guess I feel 19 bytes of okay about it. This uses the fact that `8+9^z` is equivalent to either `-3` or `-1` mod 10 depending on whether z is even or odd. So I use `A~` to break the number into digits on the stack, but as I build the stack I multiply each digit by `8+9^z` where z is the current stack size. Then I add them all as the *function* stack unrolls, and print the last digit.

# Answer
> 1 votes
# JavaScript, 57 bytes

```
f=s=>s+(10-s.split``.reduce((a,b,i)=>a+b*(3-i%2*2),0)%10)

```

You can invoke it like this:

```
f("978030640615")

```

Effectively, it goes through each (digit, index) pair (`b`, `i`), and works out `i % 2` (is `i` odd?), multiplies it by 2, and subtracts it from 3. Take a look at this:

For odd numbers:

* `(i % 2)` is 1
* `((i % 2) * 2)` is 2
* `3 - ((i % 2) * 2)` is 1

For even numbers:

* `(i % 2)` is 0
* `((i % 2) * 2)` is 0
* `3 - ((i % 2) * 2)` is 3

And so we have now generated the correct multipliers. From there it is simple, just add the current accumulator value, initialised at 0, to the current character multiplied by this generated multiplier. JavaScript automatically casts string to numbers when you do this multiplication.

Calculating the last digit is done by taking the last digit (by computing the value modulo 10), and subtracting this from 10.

# Answer
> 1 votes
# K (ngn/k), 19 bytes

```
{x,$10!2+/x*12#9 7}

```

Try it online!

Uses the `9 7` instead of `1 3` trick from @Bubbler's J answer, as well as `2+/x...` to convert ASCII digits to usable numbers (e.g. "0" is 48, so adding two makes it 50 which allows it to work given the mod by 10 later).

* `12#9 7` build a 12-length list of `9 7` repeated (i.e. `9 7 9 7 9 7 9 7 9 7 9 7`)
* `x*` multiply the underlying ASCII character values by this pattern
* `2+/` seed a sum with `2` to properly offset the input digits
* `10!` mod by 10
* `$` convert result to a string
* `x,` append it to the input and return

# Answer
> 1 votes
# Pyt, 20 bytes

```
ĐąĐŁř⁺1∧2*⁺·1ᴇ%1ᴇ-~ǰ

```

Try it online!

```
Đ                          implicit input; Đuplicate
 ą                         convert to ąrray of digits
  ĐŁ                       Đuplicate and get Łength
    ř⁺1∧                   řangify [1,2,...,n], increment, and AND with 1
        2*⁺                double and increment (yielding [1,3,1,3,...])
           ·               dot product
            1ᴇ%            modulo 10
               1ᴇ-~        10 - previous result
                   ǰ       ǰoin stack with no delimiters; implicit print

```

# Answer
> 0 votes
# MATLAB - 82 chars

```
function c(i)
[i num2str(mod(10-mod(sum(str2num(i(:)).*repmat([1;3],6,1)),10),10))]

```

# Answer
> 0 votes
## R, 147 characters

```
f=function(v){s=as.numeric(strsplit(v,"")[[1]]);t=0;for(i in 1:12)if(i%%2==0)t=t+s[i]*3 else t=t+s[i];paste(v,(10-(t%%10))%%10,collapse="",sep="")}

```

Usage:

```
f("978030640615")
[1] "9780306406157"

```

# Answer
> 0 votes
# J, 25

```
,[:":10|0(-+/)"."0*1 3$~#

```

```
   f =: ,[:":10|0(-+/)"."0*1 3$~#
   f '978030640615'
9780306406157

```

# Answer
> 0 votes
**Javascript: ~~73~~ 71 chars**

```
function _(b){for(i=s=0;12>i;)s+=((i*2&2)+1)*b[i++];return b+(10-s%10)}

```

Usage:

```
_('978030640615') //"9780306406157"

```

# Answer
> 0 votes
**Clojure 264 -\> 241 characters:**

```
(defn s [a b] (let [c (count a)] (if (= 0 c) b (s (rest a) (+ b (* (if (= 0 (m c 2)) 1 3) (first a)))))))
(defn m [a b] (let [f (mod a b)] (if (= f 10) 0 f)))
(defn c [a] (str a (m (- 10 (m (s (map #(read-string %) (map str a)) 0) 10)) 10)))

```

Usage

```
(c "978030640615")

```

Non minified:

```
(defn sum [collection total]
  (let [len (count collection)]
    (if (= 0 len)
         total
         (sum (rest collection)
           (+ total
            (* (if (= 0 (mod len 2)) 1 3)
             (first collection)))))))

(defn mods [a b]
  (let [f (mod a b)]
    (if (= f 10)
      0
      f)))

(defn create [isbn]
  (str isbn
       (mods (- 10 (mods (sum (map #(read-string %) (map str isbn)) 0) 10)) 10)))

```

Usage:

```
(create "978030640615")

```

New to Clojure so I have to believe that can be knocked down.

# Answer
> 0 votes
# Tcl, 79

```
proc f c {lmap a\ b [split $c {}] {incr d [expr $a+3*$b]};list $c[expr -$d%10]}

```

# Answer
> 0 votes
# Tcl, 87 bytes

```
proc C s {lmap c [split $s ""] {incr t [expr [incr i]%2?$c:3*$c]}
list $s[expr -$t%10]}

```

Try it online!

# Answer
> 0 votes
# Tcl, 64 bytes

```
proc C s {list $s[expr ([regsub -all (.)(.) $s {-\1-3*\2}])%10]}

```

Try it online!

# Answer
> 0 votes
# Husk, 16 bytes

```
S:(→sΣz¤*or;¢"97

```

Try it online!

### Explanation

Instead of subtracting the sum from 10 I use negated coefficients, the rest is pretty self-explanatory:

```
S:(              )  -- apply the following function and append result to itself:
   →s               -- mod 10 / last digit
     Σ              -- sum
      z      ¢"97   -- zip input with ['9','7','9','7'...] under:
       ¤ (r;)       --   convert both chars to number, then
        *           --   multiply

```

# Answer
> 0 votes
# , 21 bytes

```
,10":@|1#."."+*9 7$~#

```

Try it online!

### How it works

```
,10":@|1#."."+*9 7$~#
                    #  Take length of input
               9 7$~   Repeat 9 7 that many times
          "."+*        Multiply (elementwise) to the digits
       1#.             Sum
 10   |                Modulo 10
   ":@                 Format to string
,                      Append to the end of the input string

```

The negative of `a + 3b + c + 3d + ...` modulo 10 is equal to `9a + 7b + 9c + 7d + ...` modulo 10.

# Answer
> 0 votes
# MBASIC, 106 bytes

```
1 INPUT T$:FOR I=1 TO 12 STEP 2:O=O+VAL(MID$(T$,I,1)):E=E+3*VAL(MID$(T$,I+1,1)):NEXT:PRINT 10-(O+E) MOD 10

```

It ain't pretty, but it works.

```
? 978030640615
7

```

# Answer
> 0 votes
# Kotlin, ~~120~~ ~~108~~ ~~83~~ ~~77~~ 69 bytes

```
{s->s+(10-(s.map{it.toInt()-48}.chunked(2).sumBy{it[0]+3*it[1]})%10)}

```

Try it online!

Thanks to @ovs for removing 8 bytes!!

# Answer
> 0 votes
# \>\<\>, 24 bytes

```
0{:9)68**-:nl2%2*7+*+a%!

```

Try it online!

**Explanation**

```
0                      !  # initiates sum (final digit) as 0
 {                        # get the next digit
  :9)68**-                # convert from char to int for any iteration except the last
          :n              # print the digit
            l2%2*7+*      # multiply the digit by either 9 or 7 alternately
                    +     # add to sum
                     a%   # mod sum by 10

```

# Answer
> 0 votes
# Perl 5, 48 bytes

```
sub f{"@_"=~s/(.)(.)/$t-=$1+3*$2/ger;"@_".$t%10}

```

Try it online!

Doing this as a full program would be shorter:

### Perl 5 `-p`, 31 bytes

```
s/(.)(.)/$\-=$1+3*$2/ger;$\%=10

```

Try it online!

# Answer
> 0 votes
# Jelly, 10 bytes

```
ȮD×Ðe3SN%⁵

```

Try it online!

## How it works

```
ȮD×Ðe3SN%⁵ - Main link. Takes n on the left
Ȯ          - Print n
 D         - Convert to digits
   Ðe      - To even indices:
  ×  3     -   Triple
      S    - Take the sum
       N   - Negate
        %⁵ - Mod 10
             Implicitly print this digit

```

# Answer
> 0 votes
# Go, 118 bytes

```
func f(n int)int{o,e:=0,0
for i,x:=1,n;i<13;i++{if i%2==0{o+=x%10}else{e+=x%10}
x/=10}
return n*10+(10-(o+3*e)%10)%10}

```

Attempt This Online!

# Answer
> 0 votes
# Japt, 14 bytes

I/O as a string.

```
+¬xÈ*YgDìÃìÌnA

```

Try it

```
+¬xÈ*YgDìÃìÌnA     :Implicit input of string U
+                  :Append
 ¬                 :  Split U
  x                :  Reduce by addition
   È               :  After passing each element at index Y through the following function
    *              :    Multiply by
     Yg            :      Index Y into
       D           :        13
        ì          :        To digit array
         Ã         :  End reduction
          ì        :  To digit array
           Ì       :  Last element
            n      :  Subtract from
             A     :   Ten

```

# Answer
> 0 votes
# Thunno, \\$ 17 \log\_{256}(96) \approx \\$ 13.99 bytes

```
DZLdZl.SAu3*+n10%

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
DZLdZl.SAu3*+n10%  # Implicit input
DZL                # Print the input without a trailing newline
   dZl             # Convert it to a list of digits and uninterleave
      .SAu         # Sum each list and dump onto the stack
          3*+      # Multiply the top one by 3 and add together
             n10%  # Negate and mod by 10
                   # This is output implicitly, concatenated onto the input,
                   # which was output without a newline at the start

```

# Answer
> 0 votes
# Thunno 2, 10 bytes

```
zʂẸ3×+ṄT%a

```

Attempt This Online!

#### Explanation

```
zʂẸ3×+ṄT%a  # Implicit input   ->  978030640615
z           # Uninterleave     ->  [[9,8,3,6,0,1],[7,0,0,4,6,5]]
 ʂ          # Sum each         ->  [27,22]
  Ẹ         # Dump onto stack  ->  27, 22
   3×       # Triple           ->  27, 66
     +      # Add              ->  93
      Ṅ     # Negate           ->  -93
       T%   # Mod 10           ->  7
         a  # Append to input  ->  9780306406157
            # Implicit output

```

# Answer
> -1 votes
## Python

```
>>>r=input()
>>>a=0
>>>for x in r[::2]:
    a+=int(x)
>>>for x in r[1::2]:
    a+=int(x)*3
>>>a=(10-(a%10))%10
print(r+str(a))

```

---
Tags: code-golf, checksum
---


title: Divisibility Streak

text:
# Question
Title: Divisibility Streak
We can define the Divisibility Streak `k` of a number `n` by finding the smallest non-negative integer `k` such that `n+k` is not divisible by `k+1`.

### Challenge

In your language of choice, write a program or function that outputs or returns the Divisibility Streak of your input.

### Examples:

```
n=13:
13 is divisible by 1
14 is divisible by 2
15 is divisible by 3
16 is divisible by 4
17 is not divisible by 5

```

The Divisibilty Streak of `13` is `4`

```
n=120:
120 is divisible by 1
121 is not divisible by 2

```

The Divisibilty Streak of `120` is `1`

### Test Cases:

```
n      DS
2      1
3      2
4      1
5      2
6      1
7      3
8      1
9      2
10     1
2521   10

```

More test cases can be found here.

### Notes

### Rules

* You can assume the input is greater than 1.

### Scoring

:The submission with the lowest score wins.

# Answer
> 8 votes
# Pyth, ~~6~~ 5 bytes

```
f%tQh

```

Try it online!

# Answer
> 19 votes
# Java 8, ~~44~~ ~~42~~ ~~41~~ 39 bytes

<sup>*Crossed out 44 is still regular 44 ;(*</sup>

```
n->{int r=0;for(;~-n%--r<1;);return~r;}

```

-2 bytes thanks to *@LeakyNun*.
-1 byte thanks to *@TheLethalCoder*.
-2 bytes thanks to *@Nevay*.

**Explanation:**

Try it here.

```
n->{                 // Method with integer as parameter and return-type
  int r=0;           //  Result-integer (starting at 0)
  for(;~-n%--r<1;);  //  Loop as long as `n-1` is divisible by `r-1`
                     //   (after we've first decreased `r` by 1 every iteration)
  return~r;          //  Return `-r-1` as result integer
}                    // End of method

```

# Answer
> 9 votes
# Haskell, 35 bytes

```
f n=[k|k<-[1..],rem(n+k)(k+1)>0]!!0

```

Try it online!

Using `until` is also 35 bytes

```
f n=until(\k->rem(n+k)(k+1)>0)(+1)1

```

# Answer
> 6 votes
# Husk, 7 bytes

```
ḟ§%→+⁰N

```

Try it online!

# Answer
> 6 votes
# 05AB1E, ~~7~~ 6 bytes

```
Ý+āÖ0k

```

Try it online!

**Alternate 7 byte solutions:**
`<DLÖγнg`
`Ls<ÑKн<`

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~16~~ ~~14~~ 13 bytes

```
⊃∘⍸⍳(×+∘×|+)⊢

```

-1b thanks to Adám

Try it online!

Previous solution made tacit (i.e. using trains)

---

```
{⊃⍸×(1+⍳⍵)|⍵+⍳⍵}

```

Try it online!

Only my second APL answer so I'm sure it can be golfed further!

Justification for only searching up to 2n is due to Bertrand's Postulate which states that for any n\>3, there exists a prime number between n and 2^n-2. Since by definition a prime only has factors of itself and 1, it will always terminate the divisibility streak.

## Explanation

```
{⊃⍸×(1+⍳⍵)|⍵+⍳⍵}  ⍝
{              }  ⍝ dfn, in this case taking a single argument (e.g. 13) mapped to ⍵
             ⍳⍵   ⍝ computes array of digits 0,1,2,3,4...,12
           ⍵+     ⍝ adds the original argument to each element of this array - 13,14,15,16...25
    (1+⍳⍵)        ⍝ computes a new array from 1...13
          |       ⍝ applies modulo to elements at the same index across the two arrays, e.g. 13%1,14%2,15%3,16%4,17%5...26%14 = 0 0 0 0 2...12
   ×              ⍝ converts any number >1 to 1, e.g. 0 0 0 0 1...1
  ⍸               ⍝ find the index of all 'true's. e.g. 4 6 7 8 9 10 12 13
 ⊃                ⍝ take the first, e.g. 4

```

# Answer
> 5 votes
# JavaScript (ES6), 28 bytes

```
n=>g=(x=2)=>++n%x?--x:g(++x)

```

---

## Test it

```
o.innerText=(f=

n=>g=(x=2)=>++n%x?--x:g(++x)

)(i.value=2521)();oninput=_=>o.innerText=f(+i.value)()
```

```
<input id=i><pre id=o>
```

# Answer
> 5 votes
# Perl 5, ~~23~~ 21 + 1 (-p) = 22 bytes

```
1until$_++%++$\}{$\--

```

Try it online!

# Answer
> 5 votes
# Mathematica, ~~30~~ 27 bytes

```
0//.i_/;(i+1)∣(#+i):>i+1&

```

An unnamed function that takes an integer argument.

Try it on Wolfram Sandbox

Usage:

```
0//.i_/;(i+1)∣(#+i):>i+1&[2521]

```

> `10`

# Answer
> 4 votes
# Python 2, 35 bytes

```
f=lambda n,x=1:n%x<1and-~f(n+1,x+1)

```

Try it online!

# Answer
> 4 votes
# K (oK), ~~23~~ 15 bytes

```
#1_(~!/)(1+)\1,

```

Try it online!

**Explanation:**

```
(~!/)(1+)\1, / the solution
          1, / prepend 1 to input
     (1+)\   / iterate, increasing by 1
(~!/)        / until the modulo (!) is not (~) zero

```
* -8 bytes thanks to @Traws!

# Answer
> 3 votes
# Python 2, ~~43~~ 41 bytes

*Saved 2 bytes thanks to Leaky Nun!*

```
i=input();k=1
while~-i%-~k<1:k+=1
print k

```

Try it online!

# Python 2, 40 bytes

```
f=lambda i,k=1:~-i%-~k<1and f(i,k+1)or k

```

Try it online!

# Answer
> 3 votes
# Cubix, 17 bytes

```
)uUqI1%?;)qUO(;/@

```

Try it online!

Cubified

```
    ) u
    U q
I 1 % ? ; ) q U
O ( ; / @ . . .
    . .
    . .

```
* `I1` setup the stack with input and divisor
* `%?` do mod and test
    + `;)qU)uqU` if 0 remove result and increment input and divisor. Bit of a round about path to get back to `%`
    + `/;(O@` if not 0, drop result, decrement divisor, output and exit

Watch it run

# Answer
> 2 votes
# Japt , ~~9~~ ~~8~~ ~~7~~ 5 bytes

```
N°u°U

```

Try it

## Original (w/o flag), 7 bytes

```
@°uXÄ}a

```

Test it

---

## Explanation

Implicit input of integer `U`.

```
@     }a

```

Return the first integer that returns a truthy value (a number `>0`) when passed through a function (with `X` being the current integer) ...

```
°

```

That postfix increments `U` ...

```
uXÄ

```

And modulos it (`u`) by `X+1`.

# Answer
> 2 votes
# Python 2, ~~44~~ 40 bytes

*-4 bytes thanks to Leaky Nun.*

```
f=lambda n,x=1:~-n%-~x and x or f(n,x+1)

```

Try it online!

# Answer
> 2 votes
# C# (Mono), ~~41~~ 39 bytes

```
n=>{int r=0;while(~-n%--r<1);return~r;}

```

Essentially a port of @Kevin Cruijssen's Java 8 answer with further golfing.

Try it online!

# Answer
> 2 votes
# Swift 4, 56 bytes

This is a full function `f`, with an integer parameter `i` that prints the output.

```
func f(i:Int){var k=0;while(i-1)%(k+1)<1{k+=1};print(k)}

```

**Try it here.**

# Swift 4, 56 bytes

This is an anonymous function, that returns the result.

```
{var k=0;while($0-1)%(k+1)<1{k+=1};return k}as(Int)->Int

```

**Try it here.**

**Check out the Test Suite!**

# Answer
> 2 votes
# Ruby, ~~34~~ ~~32~~ 31 bytes

```
f=->n,d=1{n%d<1?1+f[n+1,d+1]:0}

```

A recursive lambda. Still new to Ruby, so suggestions are welcome!

Try it online!

# Answer
> 2 votes
# dc, 28 bytes

```
1si[1+dli1+dsi%0=M]dsMxli1-p

```

Try it online!

This feels *really* suboptimal, with the incrementing and the final decrement, but I can't really see a way to improve on it. Basically we just increment a counter `i` and our starting value as long as value mod `i` continues to be zero, and once that's not true we subtract one from `i` and print.

# Answer
> 2 votes
# Gaia, 8 bytes

```
@1Ė₌)†↺(

```

Try it online!

### Explanation

```
@         Push input (call it n).
 1        Push 1 (call it i).
      ↺   While...
  Ė₌       n is divisible by i:
    )†     Increment both n and i.
       (  Decrement the value of i that failed this test and print.

```

# Answer
> 2 votes
# J, 17 bytes

```
[:{.@I.>:@i.|i.+]

```

Try it online!

I think there's still room for golfing here.

### Explanation (ungolfed)

```
[: {.@I. >:@i. | i. + ]
                 i. + ]  Range [n,2n)
                 i.       Range [0,n)
                    +     Added to each
                      ]   n
         >:@i. | i. + ]  Divisibility test
         >:@i.            Range [1,n+1)
               |          Modulo (in J, the arguments are reversed)
                 i. + ]   Range [n,2n)
    {.@I.                Get the index of the first non-divisible
       I.                 Indices of non-zero values
    {.                    Head

```

The cap (`[:`) is there to make sure that J doesn't treat the last verb (`{.@I.`) as part of a hook.

The only sort of weird thing about this answer is that `I.` actually duplicates the index of each non-zero number as many times as that number's value. e.g.

```
   I. 0 1 0 2 3
1 3 3 4 4 4

```

But it doesn't matter since we want the first index anyways (and since `i.` gives an ascending range, we know the first index will be the smallest value).

Finally, here's a very short proof that it is valid to check division only up to `n`.

We start checking divisibility with `1 | n`, so assuming the streak goes that far, once we get to checking divisibility by `n` we have `n | 2n - 1` which will never be true (`2n - 1 ≡ n - 1 (mod n)`). Therefore, the streak will end there.

# Answer
> 2 votes
# Japt, 7 bytes

```
õ b!%UÉ

```

Test it online!

# Answer
> 2 votes
# x86 Machine Code, 16 bytes

```
49                 dec    ecx        ; decrement argument
31 FF              xor    edi, edi   ; zero counter

                Loop:
47                 inc    edi        ; increment counter
89 C8              mov    eax, ecx   ; copy argument to EAX for division
99                 cdq               ; use 1-byte CDQ with unsigned to zero EDX
F7 FF              idiv   edi        ; EDX:EAX / counter
85 D2              test   edx, edx   ; test remainder
74 F6              jz     Loop       ; keep looping if remainder == 0

4F                 dec    edi        ; decrement counter
97                 xchg   eax, edi   ; move counter into EAX for return
C3                 ret               ;  (use 1-byte XCHG instead of 2-byte MOV)

```

The above function takes a single parameter, `n`, in the `ECX` register. It computes its divisibility streak, `k`, and returns that via the `EAX` register. It conforms to the 32-bit fastcall calling convention, so it is easily callable from C code using either Microsoft or Gnu compilers.

The logic is pretty simple: it just does an iterative test starting from 1. It's functionally identical to most of the other answers here, but hand-optimized for size. Lots of nice 1-byte instructions there, including `INC`, `DEC`, `CDQ`, and `XCHG`. The hard-coded operands for division hurt us a bit, but not terribly so.

Try it online!

# Answer
> 2 votes
# PHP, 34 bytes

```
for(;$argv[1]++%++$r<1;);echo$r-1;

```

Try it online!

Simple enough. Checks the remainder of division (mod) each loop while incrementing each value, outputs when the number isn't divisible anymore.

# Answer
> 2 votes
# Befunge, 19 bytes

```
#v_1+::&+1-\%
1<@.-

```

Try it online!

# Answer
> 2 votes
# Jelly, 7 bytes

```
Ḷ+%RTḢ’

```

Try it online!

Explanation:

```
Ḷ+%RTḢ’  main link, argument: n
Ḷ+       [n, 2n-1]
   R     [1, n]
  %      modulo
    TḢ   index of first truthy value (first value where k+1 does not divide n+k), 1-indexed
      ’  decrement

```

# Answer
> 2 votes
# Keg, 17 bytes

```
®n0&{©n⑻+⑹⑻%0=|}⑺

```

Try it online!

# Answer
> 2 votes
# K4, ~~27~~ 25 bytes

**Solution:**

```
*(1+)/[{y=x*_y%x}. 1+;]1,

```

**Explanation:**

Pretty naive. Start with list of \[1, x\] and increment both until no longer divisible.

```
*(1+)/[{y=x*_y%x}. 1+;]1, / the solution
                       1, / prepend input with 1
 (  )\[              ;]   / (loop)\[condition;start]
       {        }.        / lambda taking implicit x & y
                   1+     / add 1 (vectorised) [1, 13] => [2, 14]
             y%x          / divide y by x
            _             / floor
          y*              / multiply by x
        y=                / equals y?
  1+                      / add 1 (vectorised) [1, 13] => [2, 14]
*                         / take first [2, 14] => 2

```

# Answer
> 2 votes
# PowerShell Core, 30 bytes

```
for(;!($args[0]++%++$i)){}$i-1

```

Try it online!

# Answer
> 2 votes
# Vyxal, 7 bytes

```
?+n›%)Ṅ

```

Try it online!

Explanation:

```
     )   # Lambda f from beginning of program
      Ṅ  # First non-negative integer n such that f(n) is truthy
?        # Push the input
 +       # Add n to it
    %    # Modulo
  n›     # N incremented

```

# Answer
> 2 votes
# \>\<\>, 20 bytes

```
0\1-n;
?\1+:@$:1+}$%

```

Try it online!

# Answer
> 2 votes
# Pyt, 14 bytes

```
ĐřĐ0↔⁻⇹|¬*ž↓⁻+

```

Try it online!

Determines the first positive integer that does not divide \\$n-1\\$.

```
Đ                   implicit input; Đuplicate
 ř                  řangify
  Đ                 Đuplicate
   0                push 0 (so the next action will work properly)
    ↔               flip the stack
     ⁻              decrement
      ⇹             swap top two items
       |¬           divisibility test; negate
         *ž↓        multiply element-wise, remove žeros, get minimum
            ⁻       decrement
             +      add to get rid of pesky 0; implicit print

```

# Answer
> 2 votes
# Arturo, 32 bytes

```
$[n][1while[0=%n-+1<=<=][+1]dec]

```

Try it

# Answer
> 2 votes
# Nibbles, 5.5 bytes

```
?,~~%+@$+$~

```

Attempt This Online!

```
? Find the index of the first item
,  in the numbers from 1 to
~   infinity
~  such that the result of the following is positive
%   modulo
+    add
@     the input
$     the number
+    add
$     the number
~     1

```

# Answer
> 2 votes
# Thunno 2, 5 bytes

```
Ƙ+n⁺%

```

Try it online!

#### Explanation

```
Ƙ+n⁺%  # Implicit input
Ƙ      # Find the first positive integer, n, such that:
 +     #  input + n
    %  #  mod
  n⁺   #  n + 1
       #  is truthy (non-zero)
       # Implicit output

```

# Answer
> 1 votes
# SOGL V0.12, 8 bytes

```
]e.-ē⁴I\

```

Try it Here!

Not bad for a language which is made for a completely different type of challenges.

Explanation:

```
]         do .. while top of the stack is truthy
 e          push the variable E contents, by default user input
  .-        subtract the input from it
    ē       push the value of the variable E and then increase the variable
     ⁴      duplicate the item below one in the stack
      I     increase it
       \    test if divides
            if it does divide, then the loop restarts, if not, outputs POP which is `e-input`

```

# Answer
> 1 votes
# Mathematica, 40 bytes

```
Min@Complement[Range@#,Divisors[#-1]-1]&

```

Try it online! (Mathics)

Mathematical approach, n+k is divisible by k+1 if and only if n-1 is divisible by k+1. And n-1 is not divisible by n, so `Range@#` is enough numbers.

Originally I intend to use `Min@Complement[Range@#,Divisors[#-1]]-1&`, but this also work.

# Answer
> 1 votes
## Julia 0.6.0 (47 bytes) (38 bytes)

`n->(i=1;while isinteger(n/i) i+=1;n+=1 end;i-1)`

`n->(i=1;while n%i<1 i+=1;n+=1end;i-1)`

Try it online!

9 bytes were cut thanks to Mr.Xcoder

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

```
i;f(n){for(i=1;++n%++i<1;);n=i-1;}

```

Try it online!

# Answer
> 1 votes
## Batch, 70 bytes

```
@set/an=%1-1,i=0
:l
@set/ai+=1,r=n%%~i
@if %r%==0 goto l
@echo %i%

```

All this is doing is finding the largest `i` such that `LCM(1..i)` divides `n-1`.

# Answer
> 1 votes
# , ~~43~~ 37 bytes

```
n=scan();which((n+1:n)%%(1:n+1)>0)[1]

```

Try it online!

# Answer
> 1 votes
# Aceto, ~~28~~ 27 bytes

```
[;`%
I)@]
iIk2I(D(
rk[(&Xpu

```

I could save one byte if I don't have to exit.

### Explanation:

We use three stacks: The left stack holds a counter starting at 2, the right one holds the given number (or its increments), the center stack is used for doing the modulo operations. We could, of course, do everything in one stack, but this way we can set the outer stacks to be "sticky" (values that are popped aren't really removed) and save ourselves many duplication operations. Here's the method in detail:

Read an integer, increment it, make the current stack sticky, and "move" it (and ourselves) to the stack to the left:

```
iI
rk[

```

Go one more stack to the left, push a literal 2, make this stack sticky, too. Remember this position in the code (`@`), and "move" a value and ourselves to the center stack again.

```
  @]
  k2
   (

```

Now we test: Is the modulo of the top two numbers not 0? If so, jump to the end, otherwise go one stack to the right, increment, and push the value and us to the middle. Then go to the left stack, increment it, too, and jump back to the mark that we set before.

```
[;`%
I)
    I(
    &

```

When the result of the modulo was not zero, we invert the position the IP is moving, go one stack to the left (where our counter lives), decrement it, and print the value, then exit.

```
      D(
     Xpu

```

# Answer
> 1 votes
## F#, ~~86 bytes~~ 84 bytes

```
let s n =
    let rec c n1 d r=if n1%d=0 then c(n1+1)(d+1)(r+1)else r
    c n 1 0

```

Try it online!

Edit: -2 characters from Oliver

# Answer
> 1 votes
# Actually, 13 bytes

```
╗1⌠u;u@╜+%⌡╓u

```

Try it online!

Explanation:

```
╗1⌠u;u@╜+%⌡╓u
╗              save n to register 0
 1⌠u;u@╜+%⌡╓   first k (starting with k=0) where the following is truthy:
   u             k+1
    ;u@╜+        n+k+1
         %       (n+k+1)%(k+1)
            u  increment

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 11 bytes

```
⊥⍨∘⌽0=⍳|-∘1

```

Try it online!

Uses the alternative representation: the highest `k` such that `1..k` divides `n-1`.

### How it works

```
⊥⍨∘⌽0=⍳|-∘1  ⍝ Input: n
        -∘1  ⍝ n minus 1
    0=⍳|     ⍝ Is divisible by 1..n?
⊥⍨∘⌽         ⍝ Count the leading ones

```

"Count leading ones" idiom can be found on APLcart.

# Answer
> 1 votes
# asm2bf, 74 bytes

Try it online!

I/O format: In most cases, it's ASCII, yet some interpreters will output numbers in decimal representation. That's why the test case has `1` return 4 =\> because in fact, `ASCII(1)` is `49`.

Golfed:

```
in r1
incr2
@l
movr3,r1
modr3,r2
ceqr3,0
cadr1,1
cadr2,1
cjn%l
decr2
outr2

```

Commented version:

```
; Read the number from the standard input.
in r1

; We start the division with 1.
inc r2

@l
    ; r3 = r1 mod r2
    mov r3, r1
    mod r3, r2

    ; if r3 is zero, then the streak
    ; isn't over.
    ceq r3, 0

    ; Pass around next number and divisor.
    cad r1, 1
    cad r2, 1

    ; Loop
    cjn %l

; Display the final result (it's always off-by-one), yet a dec fixes it.
dec r2
out r2

```

# Answer
> 1 votes
# Brachylog, 10 bytes

```
∧.ℕ+↙?f-₁ⁿ

```

Try it online!

```
 .            The output
∧             (which isn't necessarily the input)
  ℕ           is a non-negative integer, and
      f       the factors of
   +↙?        it plus the input
       -₁ⁿ    do not contain the output plus 1.

```

# Answer
> 1 votes
# JavaScript (V8), 27 bytes

```
(n,i=2)=>n%i^1?--i:f(n,++i)

```

Try it online!

# Answer
> 1 votes
# Ruby, 39 bytes

```
->x{1.step{|i|break i-1if x%i!=0;x+=1}}

```

Try it online!

# Answer
> 1 votes
# F#, 64 bytes

```
let d n=
 let mutable m,l=n,1
 while m%l=0 do m<-m+1;l<-l+1
 l-1

```

Try it online!

Simple explanation:

```
let divisibilityStreak n = // Arg: 'n'
 let mutable l = 1         // For increase the 'divisible' number
 let mutable n2 = n        // Another one for storing mutable 'n'
 while n2 % l = 0 do       // While 'n' is divisible by 'l',
  n2 <- n2 + 1             // Add 1 to both 'n2' (mutable 'n')...
  l <- l + 1               // and 'l'
 l - 1                     // Finally, return 'l - 1'

```

# Answer
> 1 votes
# jq, 34 bytes

```
. as$x|0|until((.+$x)%(1+.)>0;.+1)

```

Try it online!

---

# jq, 40 bytes

```
[range(.)as$x|(.+$x)%(1+$x)<1//-$x]|-max

```

Try it online!

# Answer
> 1 votes
# TI-Basic, ~~19~~ 21 bytes

```
Input N
Repeat remainder(N+Ans,Ans+1
Ans+1
End
Ans

```

Output is stored in `Ans` and displayed. This only works on TI-84+/SE with the 2.53 MP OS. The below version is 2 bytes bigger but works on earlier OS's.

---

### ~~21~~ 23 bytes

```
Input N
Repeat fPart((N+Ans)/(Ans+1
Ans+1
End
Ans

```

# Answer
> 1 votes
# Fig, \\$10\log\_{256}(96)\approx\\$ 8.231 bytes

```
Lt@!%mCG@}

```

Try it online!

Argh y'all's "first number satisfying f" builtins.

```
Lt@!%mCG@}
       G@} # Generate an infinite list of numbers by incrementing the input
    %      # Modulo each in that list by
     mC    # [1, 2, 3, 4, ...]
 t@        # Take while
   !       # The number is 0
L          # Length of the resulting list

```

# Answer
> 1 votes
# Risky, 7.5 bytes

```
0+0+0+0??+?\?+1

```

Try it online!

Risky happens to be very good (for its own standards) at this specific problem.

```
0+0+0+0??+?\?+1
       ?        Find the
0+0+0+0         first
                number such that
        ?       (the number
         +       plus
          ?      the input)
           \    modulo
            ?   (the number
             +   plus
              1  1)
                is non-zero

```

---
Tags: code-golf, number, division
---


title: Don't give me five!

text:
# Question
Title: Don't give me five!
**Question :**

You will be given the starting and ending integers of a sequence and should return the number of integers within it which do not contain the digit `5`. The start and end numbers should be included!

> **Examples:**
>
> 1,9 → 1,2,3,4,6,7,8,9 → Result 8
>
> 4,17 → 4,6,7,8,9,10,11,12,13,14,16,17 → Result 12
>
> 50,60 → 60 → Result 1
>
> -59,-50 → → Result 0

The result may contain five.

The start number will always be smaller than the end number. Both numbers can be also negative!

I'm very curious for your solutions and the way you solve it. Maybe someone of you will find an easy pure mathematics solution.

**Edit** This is a code-golf challenge, so the shortest code wins.

# Answer
## JavaScript (ES6), ~~36~~ 33 bytes

Takes input with currying syntax `(a)(b)`.

```
a=>F=b=>b<a?0:!/5/.test(b)+F(b-1)

```

### Formatted and commented

```
a =>                 // outer function: takes 'a' as argument, returns F
  F = b =>           // inner function F: takes 'b' as argument, returns the final result
    b < a ?          // if b is less than a
      0              //   return 0
    :                // else
      !/5/.test(b) + //   add 1 if the decimal representation of b does not contain any '5'
      F(b - 1)       //   and do a recursive call to F with b - 1

```

### Test cases

```
let f =

a=>F=b=>b<a?0:!/5/.test(b)+F(b-1)

console.log(f(1)(9))
console.log(f(4)(17))
console.log(f(50)(60))
console.log(f(-50)(-59))
```
> 21 votes

# Answer
# Jelly, ~~8~~ 7 bytes

-1 byte thanks to Dennis (use fact that indexing into a number treats that number as a decimal list)

```
rAw€5¬S

```

**TryItOnline!**

# How?

```
rAw€5¬S - Main link: from, to    e.g. -51, -44
r       - range(from, to)        e.g. [-51,-50,-49,-48,-47,-46,-45,-44]
 A      - absolute value         e.g. [51,50,49,48,47,46,45,44]
  w€    - first index of... for €ach (0 if not present)
    5   - five                   e.g. [1,1,0,0,0,0,2,0]
     ¬  - logical not            e.g. [0,0,1,1,1,1,0,1]
      S - sum                    e.g. 5

```

* The absolute value atom, `A` is necessary since a negative number cast to a decimal list has negative entries, none of which would ever be a `5` (the given example would count all eight rather than two).
> 17 votes

# Answer
# Bash \+ grep, 17 bytes

```
seq $@|grep -cv 5

```

Try it online!
> 15 votes

# Answer
# 2sable, ~~6~~ 5 bytes

Saved a byte thanks to *Adnan*

```
Ÿ5¢_O

```

Try it online!

**Explanation**

```
 Ÿ      # inclusive range
  5¢    # count 5's in each element of the range
    _   # negate
     O  # sum

```

**Note:** This works due to a bug in `¢` making the function apply itself to each element instead of counting matching elements in the list.
> 13 votes

# Answer
# Python2, ~~59~~ ~~55~~ ~~52~~ ~~51~~ ~~47~~ ~~43~~ 42 bytes

```
f=lambda a,b:a<=b and-(`5`in`a`)-~f(a+1,b)

```

A recursive solution. Thanks to @xnor for giving me motivation to find a solution using logical operators! Also, thanks to @JonathanAllan and @xnor for guiding me and chopping the byte from 43 to 42!

# Other attempts at 43 bytes

```
f=lambda a,b:a<=b and-~-(`5`in`a`)+f(a+1,b)
f=lambda a,b:a<=b and 1-(`5`in`a`)+f(a+1,b)

```
> 9 votes

# Answer
# Pyth, ~~9~~ 8 bytes

Saved a byte thanks to FryAmTheEggman!

```
lf-\5T}E

```

Explanation:

```
        Q # Input
      }E  # Form an inclusive range starting from another input
          #   order is reversed, but doesn't matter
 f-\5T    # Filter by absence of '5'
l         # Count the number of elements left

```

Try it online!
> 6 votes

# Answer
# Bash / Unix utilities, 21 bytes

```
seq $*|sed /5/d|wc -l

```

Try it online!
> 6 votes

# Answer
# 05AB1E, ~~8~~ ~~7~~ 6 bytes

Saved a byte thanks to *Adnan*

```
Ÿ5.å_O

```

Try it online!

**Explanation**

```
Ÿ         # inclusive range
 5.å      # map 5 in y for each y in the list
    _     # logical negation
     O    # sum

```
> 6 votes

# Answer
# Haskell, 39 bytes

```
s!e=sum[1|x<-[s..e],notElem '5'$show x]

```

Try it online! Usage:

```
Prelude> 4 ! 17
12

```

Explanation:

```
             [s..e]                     -- yields the range from s to e inclusive
          x<-[s..e]                     -- for each x in this range
          x<-[s..e],notElem '5'$show x  -- if the char '5' is not in the string representation of x
       [1|x<-[s..e],notElem '5'$show x] -- then add a 1 to the resulting list
s!e=sum[1|x<-[s..e],notElem '5'$show x] -- take the sum of the list

```
> 5 votes

# Answer
# Perl 6, 23 bytes

```
{+grep {!/5/},$^a..$^b}

```

Try it online!

### How it works

```
{                     }  # A lambda.
              $^a..$^b   # Range between the two lambda arguments.
  grep {!/5/},           # Get those whose string representation doesn't match the regex /5/.
 +                       # Return the size of this list.

```
> 5 votes

# Answer
# PHP 7.1, ~~57~~ 55 bytes

```
for([,$a,$b]=$argv;$a<=$b;)$n+=!strstr($a++,53);echo$n;

```

Run with `php -r '<code>' <a> <b>`
> 4 votes

# Answer
## Groovy, ~~47~~ ~~45~~  ~~43~~ 40 bytes

```
{a,b->(a..b).findAll{!(it=~/5/)}.size()}

```

This is an unnamed closure. `findAll` is similar to adding an `if` condition in a list comprehension in python.

Try it online!
> 4 votes

# Answer
# Mathematica, ~~46~~ ~~44~~ 42 bytes

*Thanks to alephalpha and DavidC for saving 2 bytes each!*

```
Tr@Boole[FreeQ@5/@IntegerDigits@Range@##]&

```

Unnamed function taking two integer arguments and returning an integer. `IntegerDigits@Range@##` converts all the numbers between the inputs into lists of digits; `FreeQ@5` tests those lists to decide which ones do not contain any `5`. Then `Boole` converts booleans to zeros and ones, and `Tr` sums the results.

Other solutions (44 and 47 bytes):

```
Count[Range@##,x_/;IntegerDigits@x~FreeQ~5]&

```

`IntegerDigits@x~FreeQ~5` determines whether the list of digits of a number is free of 5s, and `Count[Range@##,x_/;...]&` counts how many numbers between the inputs pass that test.

```
Tr[Sign[1##&@@IntegerDigits@#-5]^2&/@Range@##]&

```

`1##&@@IntegerDigits@#-5` takes the list of digits of a number, subtracts 5 from all of them, and multplies the answers together; `Sign[...]^2` then converts all nonzero numbers to 1.
> 4 votes

# Answer
# R, 33 bytes

```
f=function(x,y)sum(!grepl(5,x:y))

```

Usage:

```
> f=function(x,y)sum(!grepl(5,x:y))
> f(40,60)
[1] 10
> f(1,9)
[1] 8
> f(4,17)
[1] 12

```
> 4 votes

# Answer
# Octave, 36 bytes

```
@(m,n)sum(all(dec2base(m:n,10)'-52))

```

Try it online!
> 4 votes

# Answer
## Ruby, ~~36~~ 35 bytes

```
->a,b{(a..b).count{|x|!x.to_s[?5]}}

```

Thx IMP1 for -1 byte
> 3 votes

# Answer
# Java 7, ~~80~~ 78 bytes

```
int c(int a,int b){int r=0;for(;a<=b;)r+=(""+a++).contains("5")?0:1;return r;}

```

**Ungolfed:**

```
int c(int a, int b){
  int r = 0;
  for (; a <= b; ) {
    r += ("" + a++).contains("5")
          ? 0
          : 1;
  }
  return r;
}

```

**Test code:**

Try it here.

```
class M{
  static int c(int a,int b){int r=0;for(;a<=b;)r+=(""+a++).contains("5")?0:1;return r;}

  public static void main(String[] a){
    System.out.println(c(1, 9));
    System.out.println(c(4, 17));
  }
}

```

**Output:**

```
8
12

```
> 3 votes

# Answer
# PowerShell, ~~42~~ 41 bytes

```
param($a,$b)$a..$b|%{$z+=!($_-match5)};$z

```

Called from the command line as .\no5s.ps1 1 20
> 3 votes

# Answer
# Regex  (Perl / PCRE), ~~160~~ 147 bytes

`^(?(?=-x*,(?!-))-?+x*(,x*(?!$))?|-?(?=(x*),-?(x*))(?=(x*),?(?=\2)(?=\3)(x*,-?|[^,]*)(x*))\4,?+x*)(?!((?=(x+)(\8{9}x*))\9)*(x{10})*x{5}\b)(?(4)\4\6)`

Try it online! \- Perl
Try it online! \- PCRE (faster)

Takes its input in unary, as two strings of `x` characters whose lengths represent the numbers, with optional `-` signs on their left side, joined by a `,` delimiter. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

Most of the logic of this regex is taken up with handling the logic of integer ranges. It's rather unnatural... literally. Natural numbers (including zero) are much easier for a regex to operate on.

```
^
(?(?=-x*,(?!-))
    # Do the following if A is negative and B is nonnegative
    -?+                     # skip sign of A, if any
    x*                      # handle the range from larger to zero, inclusive
    (,x*(?!$))?             # handle the range from B inclusive to zero exclusive
|
    # Do the following if A is nonnegative or B is negative
    -?                      # skip sign of A, if any
    (?=
          (x*),             # \2 = abs(A);
        -?(x*)              # \3 = abs(B)
    )
    (?=
        (x*),?(?=\2)(?=\3)  # \4 = what to skip so tail = the larger of A or B;
                            # tail = the larger of A or B
        (x*,-?|[^,]*)(x*)   # \6 = {the smaller of A or B} - \4
    )
    \4,?+                   # tail = the larger of A or B
    x*                      # handle the range from larger to {smaller or zero}
)
(?!                         # Negative lookahead - assert this can't match
    (
        (?=(x+)(\8{9}x*))   # \8 = floor(tail / 10); \9 = tail - \8
        \9                  # tail = tail - \9 == \8
    )*                      # Iterate the above any number of times, minimum zero
    (x{10})*x{5}\b          # Assert tail % 10 == 5
)
(?(4)\4\6)                  # If \4 is set, clamp the range at the smaller end

```

It uses conditionals, which are not supported by ECMAScript, but it'd be easy enough to port (though the regex would be even longer). The  output method is required for this algorithm to be possible in ECMAScript (there isn't yet a regex engine that can emulate ECMAScript and count possible matches, but I'm planning on adding this to RegexMathEngine soon).

# Regex (.NET), 163 bytes

`^(?=(-x*,(?!-))?)(?>-?)(?(1)|(?=(x*),-?(x*))(?=(x*),?(?=\2)(?=\3)(x*,-?|[^,]*)(x*))\4(?>,?))(?(,)(?(1),)|(?(((?=(x+)(\8{9}x*))\9)*(x{10})*x{5}\b)|())x?)*(?(4)\4\6)`

Try it online!

Returns its output as the capture count of group `\11`.

```
^
(?=
    (-x*,(?!-))?            # \1 = set iff A is negative and B is nonnegative
)
(?>-?)                      # skip sign of A, if any
(?(1)
|
    # Do the following if A is nonnegative or B is negative
    (?=
          (x*),             # \2 = abs(A);
        -?(x*)              # \3 = abs(B)
    )
    (?=
        (x*),?(?=\2)(?=\3)  # \4 = what to skip so tail = the larger of A or B;
                            # tail = the larger of A or B
        (x*,-?|[^,]*)(x*)   # \6 = {the smaller of A or B} - \4
    )
    \4                      # tail = the larger of A or B
    (?>,?)                  # skip sign of B, if any
)
                            # First handle the range from larger inclusive to
                            # {smaller inclusive or 0 exclusive}
(?(,)
    (?(1),)                 # If crossing from negative to nonnegative, handle
                            # the inclusive range from B to 0
|
    (?(
        (
            (?=(x+)(\8{9}x*))   # \8 = floor(tail / 10); \9 = tail - \8
            \9                  # tail = tail - \9 == \8
        )*                      # Iterate the above any number of times
        (x{10})*x{5}\b          # Assert tail % 10 == 5
      )
    |
        ()                  # Push a capture onto the \11 stack
    )
    x?                      # Advance by 1, but if already at the end, allow the
                            # loop to iterate once more so as to include 0 in
                            # the count.
)*
(?(4)\4\6)                  # If \4 is set, clamp the range at the smaller end

```

It could also be ported to an output method of the sum of the lengths of two capture groups (two, because the output can exceed the largest of the two inputs), though this would probably make it significantly longer.
> 3 votes

# Answer
# Thunno 2 `S`, 6 bytes

```
Id5ȷc~

```

(No ATO link since it's down at the moment)

#### Explanation

```
Id5ȷc~  # Implicit input   ->    1,                                  10
I       # Inclusive range  ->   [1,  2,  3,  4,  5,  6,  7,  8,  9,  10]
 d      # Cast to digits   ->  [[1],[2],[3],[4],[5],[6],[7],[8],[9],[1,0]]
   ȷ    # To each list:    ->   [1] [2] [3] [4] [5] [6] [7] [8] [9] [1,0]
  5 c   #  Count 5s        ->    0   0   0   0   1   0   0   0   0   0
     ~  # Logical NOT      ->   [1,  1,  1,  1,  0,  1,  1   1,  1,  1]
        # Implicit sum     ->                      9
        # Implicit output

```
> 3 votes

# Answer
## Swift 52 bytes

```
($0...$1).filter { !String($0).contains("5") }.count

```
> 2 votes

# Answer
# Python 2, 61 56 bytes

```
lambda a,b:len([n for n in range(a,b+1) if not"5"in`n`])

```

-5 bytes thanks to tukkaaX
> 2 votes

# Answer
## Batch, 95 bytes

```
@set/an=0,i=%1
:g
@if "%i%"=="%i:5=%" set/an+=1
@set/ai+=1
@if %i% leq %2 goto g
@echo %n%

```

Manually looping saves some bytes because I need the loop counter in a variable anyway.
> 2 votes

# Answer
# Python 2, 54 bytes

```
i,j=input();k=0
while i<=j:k+=not"5"in`i`;i+=1
print k

```

Try it online!

Not the shortest Python answer Uses same algorithm but a different way of implementing with a while loop and is not a lambda function.
> 2 votes

# Answer
# PHP, 56 bytes

```
for($i=$argv[1];$i<=$argv[2];)trim(5,$i++)&&$x++;echo$x;

```

Run like this:

```
php -r 'for($i=$argv[1];$i<=$argv[2];)trim(5,$i++)&&$x++;echo$x;' 1 9 2>/dev/null;echo
> 8

```

A version for PHP 7.1 would be 53 bytes (credits to Titus):

```
for([,$i,$e]=$argv;$i<=$e;)trim(5,$i++)&&$x++;echo$x;

```

# Explanation

```
for(
  $i=$argv[1];          # Set iterator to first input.
  $i<=$argv[2];         # Loop until second input is reached.
)
  trim(5,$i++) && $x++; # Trim string "5" with the characters in the
                        # current number; results in empty string when
                        # `5` is present in the number. If that is not
                        # the case, increment `$x`

echo$x;                 # Output `$x`

```
> 2 votes

# Answer
# C++ | in too many bytes, 165 125 thanks to Christoph!

```
int main(){int c=0;for(int i=0;i<=8;i++){int d;int n=i>=0?i:-i;while(n!=0){if(d=n%10==5){break;}n=n/10;c++;break;}}return c;}

```

I took the liberty of creating a function `e_` to determine if a 5(or any other number) is present in an integer instead of using `to_string()` and `.find()` so that must count for something. *note: `e_` is only declared as an extra function in the un-golfed version for readability.*

un-golfed:

```
int e_(int e,int i){
    int d;
    int n=i>=0?i:-i;
    while (n != 0){
        d=n%10;
        if (d==e){
        return 1;}
        n=n/10;}
        return 0;}
int main() {
    int l = 1;int h = 8;int e = 5;int c = 0;
    for(int i=l; i<=h; i++){
        if (e_(e,i)==0)
        c++;}
    return c;}

```

**How `e_` function works:**

`int n=i>=0?i:-i;` Inverses our number if it is less than 0 so it's always positive. `d=n%10;` Divides it by 10 and gets remainder (`n%base;` will always return the last digit of an integer). We check that it equals 5, if it does the number can be discarded, if not `n=n/10;` removes the end digit and loops again.
> 2 votes

# Answer
# CJam "easy pure mathematics solution", 60

```
{{Ab5+_,\_5#)<\9e]);_4f>.m9b}%}:F;q~_:z$\:*0>{((+F:-}{F:+)}?

```

Try it online

It takes the numbers in any order, in an array.

**Explanation:**

One core problem is to calculate f(n) = the number of non-5 numbers from 1 to n (inclusive) for any positive n. And the answer is: take n's decimal digits, replace all digits after the first 5 (if any) with 9, then replace all digits 5..9 with 4..8 (decrement), and convert from base 9. E.g. 1752 → 1759 → 1648 → 1\*9^3+6\*9^2+4\*9+8=1259. Basically, each digit position has 9 acceptable values, and a 5xxxx is equivalent to a 49999 because there are no more valid numbers between them.

Once we solved this, we have a few cases: if the input numbers (say a and b, a\<b) are (strictly) positive, then the result is f(b)-f(a-1). If they are negative, then we can take the absolute values, reorder them and use the same calculation. And if a\<=0\<=b then the result is f(-a)+f(b)+1.

The program first implements the function F as described above (but applied to each number in an array), then reads the input, converts the numbers to the absolute value and reorders them, and uses one of the 2 calculations above, based on whether a\*b\>0 initially.
> 2 votes

# Answer
# SmileBASIC, 55 bytes

```
INPUT S,E
FOR I=S TO E
INC N,INSTR(STR$(I),"5")<0NEXT?N

```

Nothing special, just uses `INSTR` and `STR$` to check for `5`.
> 2 votes

# Answer
## Hoon, ~~110~~ 94 bytes

Hoon's range function, `gulf`, doesn't work for signed integers, which increases the length by a bit :(

```
=+
si^f=:(curr lien test 53)
|=
{a/@s b/@s}
|-
?:
=(a b)
(f <b>)
(add (f <a>) $(a (sum -1 a)))

```

Use the signed integer library. Create a function `f`: `:(a b c d)` is a macro that expands into `(a b (a c d))` so this is `(curr lien (curr test 53))`, aka create a curried function that tests if any element of a list is 53 (`'5'`)

Create a function that takes `a` and `b`. Create a loop: if `a==b` return `f(tostring(b))`, else return `add(f(tostring(a)) recurse(a=a+1))`

```
> =f =+
  si^f=:(curr lien test 53)
  |=
  {a/@s b/@s}
  |-
  ?:
  =(a b)
  (f <b>)
  (add (f <a>) $(a (sum -1 a)))
> (f -1 -9)
8
> (f -4 -17)
12
> (f -50 -60)
1
> (f --59 --50)
0

```

(Hoon's signed integers use `-` as a prefix, so `--5` is negative 5 and `-5` is positive 5)
> 2 votes

# Answer
## C#, 77 bytes

```
(n,m)=>{var g=0;for(var i=n;i<m+1;i++)g+=(i+"").Contains("5")?0:1;return g;};

```

Anonymous lambda call.

Uses `n` (first number) and `m` (last number) as input, then checks via string containment (`"".Contains("")`).
> 1 votes

# Answer
## C ~~143~~ ~~141~~ ~~132~~ 122 bytes

```
f(a,b){j=0,k,f;for(;a<=b;a++){k=a;f=0;while(k!=0){if(abs(k%10)==5){f=1;break;}else f=0;k/=10;}if(f<1)j++;}printf("%d",j);}

```

This is a solution that adopts a mathematical approach and checks every digit for number 5. Can definitely be shortened!

Ungolfed version:

```
  void f(int a,int b)
  {
       int j=0,k=0,f=0;

       for(;a<=b;a++)
       {
          k=a;f=0;

          while(k!=0)
          {

            if(abs(k%10)==5) // If one of the digits in the number is 5, set a flag and break while loop, else reset the flag and continue checking.
            {
              f=1;
              break;
            }
            else
              f=0;

            k/=10;

          }

       if(f<1)
         j++;
      }
      printf("%d ",j);

  }

```

@TuukkaX Thanks for saving 2 bytes.

@nmjcman101 Thanks for saving 9 bytes.

@nmjcman101 Thanks for saving 10 bytes more, make so much sense. :)
> 1 votes

# Answer
# TI-BASIC, ~~37~~ 34 bytes

```
:Prompt A,B
:Delvar CFor(N,A,B
:C+not(inString(toString(N),"5→C
:End
:C

```

I believe count is correct, however toString() is only supported on the TI-84+ CE calculators which I do not have, so I was unable to count it or test it to make sure it runs correctly. I therefore counted it as 2 bytes in addition to the others which were counted directly on a TI-84.

Thx to Jakob Cornell for removing
> 1 votes

# Answer
## JavaScript (ES6), ~~58 56~~ 49 bytes

```
let f =

(s,e)=>{for(c=0;s<=e;)c+=!/5/.test(s++);return c}

console.log(f(1, 9));
console.log(f(4, 17));
console.log(f(-9, -1));
```

Golfed 7 bytes thanks to ETHproductions.
> 1 votes

# Answer
# Java 7, 77 bytes

This is an improvement of Kevins Answer, but since I don't have the reputation to comment yet, this new answer will have to do.

So what I did was:

* Replace the `indexOf` statements with `contains` (-1 byte)
* Move the incrementing part of the for-loop into the conditional statement (-2 bytes)

---

for-loop (**77 bytes**):

```
int c(int a,int b){int r=1;for(;a++<b;)r+=(""+a).contains("5")?0:1;return r;}

```

recursive (**79 bytes**):

```
int d(int r,int a,int b){r+=(""+a).contains("5")?0:1;return a!=b?d(r,a+1,b):r;}

```

**Output:**

```
8
12

8
12

```

Test it *here* !
> 1 votes

# Answer
## C#, 67 bytes

```
a=>b=>{int c=0;for(;a<=b;)c+=(a+++"").Contains("5")?0:1;return c;};

```
> 1 votes

# Answer
# MATL, 10 bytes

```
&:!V53-!As

```

Try it online!

**Explanation**

```
        % Implicitly grab two input arguments
&:      % Create an array from [input1....input2]
!V      % Convert to a string where each number is it's own row
53-     % Subtract ASCII '5' from each character.
!A      % Detect which rows have no false values (no 5's). Returns a logical array
s       % Sum the logical array to get the # numbers without 5's
        % Implicitly display the result

```
> 1 votes

# Answer
# PowerShell, ~~37~~ 36 bytes

```
($args[0]..$args[1]-notmatch5).Count

```

Try it online!
> 1 votes

# Answer
# Actually, 13 bytes

```
u@x`$'5íuY`░l

```

Try it online!

Explanation:

```
u@x`$'5íuY`░l
u@x            range(a, b+1)
   `$'5íuY`░   take where:
    $            string representation
     '5íuY       does not contain "5"
            l  length

```
> 1 votes

# Answer
# CJam, ~~18~~ 17 bytes

```
q~:S-){S+s'5&!},,

```

Input is end number followed by start number.

Try it online!

### How it works

```
q~                  Read and evaluate all input. Pushes end and start.
  :S                Save the start in S.
    -)              Subtract and increment, computing L =: end - start + 1.
      {       },    Filter [0 ... L-1]; for each N in the range:
       S+             Add S to N.
         s            Cast to string.
          '5&         Intersect with '5'.
             !        Take the logical NOT.
                ,   Compute the length of the resulting array.

```
> 1 votes

# Answer
# C++, ~~84~~ 81 + 16 = ~~100~~ 97 bytes

```
int f(int a,int b){int c;while(a<=b)c+=!~std::to_string(a++).find('5');return c;}

```

`#include<string>` \- +16

Ungolfed:

```
int func(int start, int end) {
  // Defaults to 0
  int count;

  // Iterates from start to end (inclusive) and increments the count by one
  // if '5' is not found
  while (start <= end)
    count += !~std::to_string(start++).find('5');

  return count;
}

```

The function itself should be pretty clear. I essentially just iterate from `start` (or `a`) to `end` (or `b`). The only more complex line is this:

```
count += !~std::to_string(start++).find('5');

```

However it is also easiy explained. `find` returns `std::npos` which is the maximum value `size_t` can hold (exact value depends on how the compiler defines it) when the character cannot be found. Which essentially means the it is an integer value filled with binary ones. `~` performs a binary not, meaning that the value is 0 when no 5 character could be found and not 0 when it could. Then `!` converts it to a `bool` (0 =\> `false`, everything else =\> `true`) and itverts it. So now when the 5 could be found the value is false and true if it could not. Then it gets added to the count variable. (`true` =\> 1, `false` =\> 0).

Try it online!

@Christoph Thanks for giving me the idea to save 3 bytes
> 1 votes

# Answer
# Perl 5, 29 bytes

```
perl -le 'print 0+grep!/5/,shift..shift' 4 17               #prints 12

```
> 1 votes

# Answer
# Vyxal `s`, 5 bytes

```
ṡ5vc†

```

Try it Online!

Port of the 05ab1e/2sable answer

## Explained

```
ṡ5vc†
ṡ     # inclusive range
 5vc  # is the number 5 in each number?
    † # negate each item. s flag sums the list

```
> 1 votes

# Answer
# Arturo, 36 bytes

```
$=>[enumerate&..&'x->¬in?{5}~{|x|}]

```

Try it!

```
$=>[                   ; a function where inputs are assigned to &
    enumerate&..&'x->  ; count in input range; assign current elt to x
        in?{5}~{|x|}   ; is the string "5" in x converted to a string?
        ¬              ; logical not
]                      ; end function

```
> 1 votes

# Answer
# Lua, 65 bytes

```
n=0s,e=...for i=s,e do n=n+((i..''):find'5'and 0or 1)end print(n)

```

Try it online!
> 1 votes

# Answer
## C#, ~~82~~ 81 bytes

```
using System.Linq;a=>b=>Enumerable.Range(a,++b-a).Count(n=>(n+"").All(d=>d!=53));

```

Added as a separate answer as it's logic is different.
> 0 votes

# Answer
# SimpleTemplate, 63 bytes

This was harder than expected.

Expects each number as a single parameter in the class, outputting the number of element without 5.

```
{@eachargv as_}{@if"~5~"is not matches_}{@incX}{@/}{@/}{@echoX}

```

**Ungolfed**

```
{@each argv as argument}
    {@if "~5~"is not matches argument}
        {@inc result}
    {@/}
{@/}
{@echo result}

```
> 0 votes

# Answer
# Perl, ~~35~~ 20+1 bytes

```
$\+=!/5/ for$_..<>}{

```

*After considerable help from @Dada in the comment below, this turned into a beautiful 20 bytes - plus 1 for the p. I've left my original answer below, for posterity.*

```
for(shift..shift){$z+=!/5/}print$z;

```

Call from command line as no5s.pl 1 20.

First Perl golf, so hopefully someone can improve it :)

Also using Strawberry Perl on Windows, so I can run no5s.pl 1 20 directly on the command line and it works - might try using perl -e ...
> 0 votes

# Answer
# Clojure, 73 bytes

```
(fn[i a](count(for[n(range i(inc a)):when(every? #(not=\5 %)(str n))]n)))

```

I had to rollback my previous "improvement", as somehow `count` was dropped from the new version, and it ended up being longer when I fixed it.

Filters the range of numbers; selecting only the numbers where every digit is not a 5.

```
(defn count-minus-5 [mi ma]
  (count ; Get the length of the resulting list
    ; Comprehension over the range mi(n) to ma(x).
    (for [n (range mi (inc ma))
          ; Only allow the number when every digit isn't a 5.
          :when (every? #(not= \5 %) (str n))]
      n)))

```
> 0 votes

# Answer
## QBIC, ~~33~~ 32 bytes

*Saved a byte by reversing the conditional and moving the increment to ELSE*

```
::[a,b|~instr(!c$,@5`)|\d=d+1}?d

```

Explanation:

```
::       get a and b from the command line
[a,b|    FOR c = a; c <= b; c++
~instr(  IF indexOf ( instr is a QBasic function that doesn't have a QBIC equivalent)
    !c$  our loop iterator cast to string
    ,@5` a literal 5
)        instr returns 0 if it didn't find '5', which is truthy.
|        THEN --> Don't do anything for values with a '5'
\d=d+1   ELSE count this number into the total
}        Close all constructs (END IF, NEXT c)
?d       Print 'd': the total number of numbers without a '5'

```
> 0 votes

# Answer
# Perl 6, 21 bytes

```
+(+*..+*).grep:{!/5/}

```

Basically equivalent to smls's solution, but I was able to shave off a couple of bytes by expressing the range as `(+*..+*)` and eliminating the brackets. (The plusses are necessary, otherwise the stars would be interpreted as negative or positive infinity rather than as arguments to the WhateverCode lambda.)
> 0 votes

# Answer
# Scala, 51 bytes

```
(a:Int,b:Int)=>a to b map{_+""indexOf "5"}count(0>)

```

I haven't been able to concisely combine the map and count.
> 0 votes

# Answer
## Clojure, 64 bytes

```
#(count(for[i(range % (inc %2)):when(not(some #{\5}(str i)))]i))

```
> 0 votes

# Answer
# C++ (function), 115

```
int f(int a,int b){int r=b-a+1,t;while((t=a++)<=b)while(t!=0)if(abs(t)%10==5){r--;break;}else t/=10;std::cout<<r;}

```

# C++ (full), 143

```
#include<iostream>
int main(){int a=0,b=4,r=b-a+1,t;while((t=a++)<=b)while(t!=0)if(abs(t)%10==5){r--;break;}else t/=10;std::cout<<r;return 0;}

```

Ungolfed version:

```
#include<iostream>
int main()
{
    int a=0, b=4, r = b-a+1, t;
    while((t = a++) <= b)
        while(t != 0)
            if(abs(t) % 10 == 5)
            {
                r--;
                break;
            }
            else
                t /= 10;
    std::cout<<r;
    return 0;
}

```
> 0 votes

# Answer
# Java 8, 68 bytes

```
(a,b)->IntStream.range(a,b+1).map(i->(""+i).contains("5")?0:1).sum()

```

This is basically just a rewrite of the Java7 solution by @Kevin Cruijssen to Java8. And I hope we don't care about imports here, otherwise it would be longer by 17 bytes due to the package).

**Ungolfed:**

```
(a,b)->IntStream.range(a,b+1)
  .map(i->(""+i).contains("5")?0:1)
  .sum()

```

**Test code:**

Try it here.

```
import java.util.function.BiFunction;
import java.util.stream.IntStream;

class M {
  public static void main (String[] args) {
    BiFunction<Integer, Integer, Integer> dontGimme5 =
      (a,b)->IntStream.range(a,b+1).map(i->(""+i).contains("5")?0:1).sum();
    System.out.println(dontGimme5.apply(1,9));
    System.out.println(dontGimme5.apply(4,17));
    System.out.println(dontGimme5.apply(-50,-59));
  }
}

```

**Output:**

```
8
12
0

```
> 0 votes

# Answer
# C++, 187 bytes

```
int f(int a,int b){int r=0;for(int i=a;i<=b;i++){r++;for(int j=0;j<floor(log(abs(i)));j++){int k=floor(abs(i)%int(pow(10,j+1))/pow(10,j));if(k==5){r--;break;}}}return r;}

```

`#include <cmath>` \- 16 bytes

I couldn't think of a purely mathematical way, so I did this.

1. Loop through a to b
2. Calculate the length with floor(log(abs(i)))
3. Get numbers of each digit with floor(abs(i)%int(pow(10, j + 1)) / pow(10,j))
4. If it is 5, subtract then move to next number

Still, isn't practical for code-golf, but used much math as I could.

Try it online!
> 0 votes

# Answer
# TI-Basic, 43 bytes

Since linear regression to string is so costly, let's try a different approach.

```
DelVar AInput
For(I,X,Y
1
For(J,1,9
Ans and 5≠int(10fPart(I/10^(J
End
A+Ans→A
End

```

**Old method, 55 bytes**

Majority of the program size is converting number to string through linear regression... why wasn't there a built-in for this?

```
DelVar AInput
For(I,X,Y
{0,1→L₁
{0,A→L₂
LinReg(ax+b) Y₁
Equ►String(Y₁,Str1
A+not(inString(Str1,"5→A
End

```

P.S. (For both methods:) Since the last statement evaluated by the program is that seventh line, it will return the value as normal through `Ans`. Also, `Input` stores to `X` and `Y` similar to `Prompt X,Y`.
> 0 votes

---
Tags: code-golf, math
---