title: Pronounce numbers

text:
# Question
Title: Pronounce numbers
# Concept

Remembering numbers can be difficult. Remembering a word may be easier. In order to memorize big numbers, I created a way to pronounce them in a leetspeak-like way.

# Rules

Each digit is first replaced by its corresponding letter:

```
0 => O
1 => I
2 => R
3 => E
4 => A
5 => S
6 => G
7 => T
8 => B
9 => P

```

After the replacement, two additional things are done to improved pronunciation:

* Between two consonants, a `U` is added.
* Between two vowels, a `N` is added.

# Examples/test cases

```
512431 => SIRANENI
834677081 => BENAGUTUTOBI
3141592 => ENINANISUPUR
1234567890 => IRENASUGUTUBUPO
6164817 => GIGABIT

```

# What's impossible

* Letters and numbers mixed in the same word
* Two successive consonants or two successive vowels
* Letters that are not in the list above
* Other characters

# Rules

The goal of this is to create a 2-way translator for this concept.

* Your program must first understand by itself if it's letter-to-number or number-to-letter translation.
* It must check for the entry to be properly formed.
* If everything is correct, display the translation.
* Else, display an error message, nothing, return a falsey value or crash the program.

# Details

* The input number/string can be entered in whatever format you want (stdin, argument, ...)
* This is , so shortest answer wins.
* Standard loopholes are forbidden.

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

Takes input as a string in both translation ways. Returns either the translation as a string or `false` in case of an invalid input.

```
f=(n,k)=>(t=n.replace(/./g,(c,i)=>1/n?(!i|p^(p=27>>c&1)?'':'UN'[p])+s[c]:~(x=s.search(c))?x:'',p=s='OIREASGTBP'),k)?t==k&&n:f(t,n)

```

### Demo

```
f=(n,k)=>(t=n.replace(/./g,(c,i)=>1/n?(!i|p^(p=27>>c&1)?'':'UN'[p])+s[c]:~(x=s.search(c))?x:'',p=s='OIREASGTBP'),k)?t==k&&n:f(t,n)

console.log(f("512431"))          // SIRANENI
console.log(f("834677081"))       // BENAGUTUTOBI
console.log(f("3141592"))         // ENINANISUPUR
console.log(f("1234567890"))      // IRENASUGUTUBUPO
console.log(f("6164735732"))      // GIGATESUTER

console.log(f("SIRANENI"))        // 512431
console.log(f("BENAGUTUTOBI"))    // 834677081
console.log(f("ENINANISUPUR"))    // 3141592
console.log(f("IRENASUGUTUBUPO")) // 1234567890
console.log(f("GIGATESUTER"))     // 6164735732

console.log(f("AB23"))            // false
console.log(f("AEI"))             // false
console.log(f("ZZ"))              // false
```

# Answer
> 2 votes
# Japt, ~~61~~ ~~59~~ ~~92~~ ~~85~~ 84 bytes

> I'm offline for most of the (long) weekend, if any more issues are discovered with this, please ask a mod to delete it for me until such a time as I can fix it.

Takes input as a string for both operations and returns a string for both as well or `false` for invalid input.Assumes number inputs will always contain multiple digits, add 1 byte replacing  with `Un<space>` if that's not valid. Returns `false` for test case `GIGATESTER` but, according to the rules, that *should be* invalid input.

---

```
V="OIREASGTBP"UÉ?¡VgXÃe"%v"²_i1'NÃe"%V"²_i1'UÃ:!Uè"%v%v|%V%V|[^{V}NU]" ©Ur"N|U" £VaX

```

**Try it:** Numbers -\> Letters or Letters -\> Numbers

---

* ~~2~~ 4 bytes saved thank to obarakon, who also convinced me to take this up again after I abandoned it earlier. I wish he hadn't!
* ~~33~~ ~~26~~ 25(!) bytes sacrificed implementing a quick fix (i.e., yet to be fully golfed) to check input validity.

---

## Explanation

(Yet to be updated to the latest version)

```
                          :Implicit input of string U.
V="..."                   :Assign the string of letters to variable V, in order.
UÉ                        :Subtract 1 from U, which will give a number (truthy) if the input is a number or NaN (falsey) if the input is a string.
?                         :If it's a number then
¡                         :    Map over the input string, replacing each character (digit) with ...
VgX                       :      the character in string V at index X, the current digit.
Ã                         :    End mapping.
e                         :    Recursively replace ...
"%v"²                     :      every occurrence of 2 vowels (RegEx) ...
_i1'N                     :      with the current match with an "N" inserted at index 1.
Ã                         :    End replacement.
e                         :    Another recursive replacement of ...
"%V"²                     :      every occurrence of 2 non-vowel characters (i.e., consonants) ...
_i1'U                     :      with the current match with a "U" inserted at index 1.
Ã                         :    End replacement.
:                         :Else, if it's a string then
Uè"%v%v|%V%V|[^{V}NU]"    :    Count the number of matches of 2 successive vowels OR 2 successive non-vowels OR any character not in contained in string V plus N & U.
                          :    (The longest part of this code is the fecking input validation!)
?                         :    If that count is greater than 0 then
T                         :       Return 0.
:                              Else
Ur"N|U"                   :        Replace every occurrence of "N" OR "U" in string U with nothing.
£                         :        Map over the string, replacing each character (letter) with ...
VaX                       :         the index of the current character X in string V.
                          :Implicit output of resulting string

```

# Answer
> 2 votes
# Python 3, 147 bytes

```
lambda c:c in"0134"
def f(n):
 o="";a=b=1-x(n[0])
 for i in n:
  a=x(i)
  if a==b:o+="UN"[a]
  o+="OIREASGTBP"["0123456789".index(i)];b=a
 print(o)

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), ~~416~~ ~~410~~ ~~399~~ ~~382~~ ~~376~~ 370 bytes

-2 bytes thanks to @Cyoce

-17 more bytes thanks to an idea by @Cyoce

-6 bytes thanks to @KevinCruijssen

```
s->{String c="[RSGTBP]",v="[OIEA]",o="([256789])",e="([0134])";boolean b=s.matches("(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+".replace("c",c).replace("v",v));int i=-1;for(s=b?s.replaceAll("[UN]",""):s.matches("[0-9]+")?s.replaceAll(e+"(?="+e+")","$1N").replaceAll(o+"(?="+o+")","$1U"):i/0+"";i<9;s=b?s.replace(v,c):s.replace(c,v)){c=++i+"";v="OIREASGTBP".charAt(i)+"";}return s;}

```

Try it online!

Ugh, java replacement is so verbose.

Function which takes a string and returns the string translated from number -\> letter or vice versa. Crashes on invalid input (you can see this in the tio example where it outputs the correct values for the first 10 test cases and then crashes with a divide by zero error which shows in the debug view)

Ungolfed (the first and last term of the for loop are pulled out for readability)

```
s-> {
    String c="[RSGTBP]", v="[OIEA]", o="([256789])", e="([0134])";
    boolean b=s.matches("(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+".replace("c",c).replace("v",v)); // lovely regex, explained below
    int i=-1;
    s= b?
        s.replaceAll("[UN]",""); // remove N's and U's
        :s.matches("[0-9]+")?
        s.replaceAll(e+"(?="+e+")","$1N").replaceAll(o+"(?="+o+")","$1U"); // add N's and U's for separating vowels and consonants
        :i/0+""; // throw an error, looks like a sting for the ternary
    for(;i<9;) {
        c=++i+"";
        v="OIREASGTBP".charAt(i)+"";
        s=b?s.replace(v,c):s.replace(c,v); // if it started with numbers, go to letters, or vice versa
    }
    return s;
}

```

The regex for matching the numbers is simple, but here is the regex for matching the letters to numbers case

```
(c$|v$|(c|vN)(?=v)|(cU|v)(?=c))+
(                             )+   every part of the word is
 c$                                a consonant at the end of the word
   |v$                             or a vowel at the end of the word
      |(c|vN)(?=v)                 or a consonant or a vowel + N followed by a vowel
                  |(cU|v)(?=c)     or a consonant + U or a vowel followed by a consonant

with c = [RSGTBP] and v = [OIEA]

```

# Answer
> 1 votes
# Java 8, ~~312~~ ~~308~~ ~~304~~ ~~301~~ ~~294~~ 290 bytes

```
s->{String r="",x="([AEIOU])",y="([BGNPRST])",z="0O1I2R3E4A5S6G7T8B9P";for(int c:s.getBytes())r+=c!=78&c!=85?z.charAt((c=z.indexOf(c)+(c<58?1:-1))<0?0:c):"";return s.matches("(("+x+y+")*"+x+"?)|(("+y+x+")*"+y+"?)|\\d*")?r.replaceAll(x+"(?="+x+")","$1N").replaceAll(y+"(?="+y+")","$1U"):"";}

```

-4 bytes (308 → 304) for a bug-fix (doesn't happen often that the byte-count decreases when I fix a bug in my code.. :D)

EDIT: Uses a different approach than @PunPun1000's Java answer by first creating the return-String in a for-loop over the characters, and then uses a more abstract regex to validate it in the return-ternary (the input is either all digits, or are the given vowels and consonants alternating (so without any adjacent vowels nor consonants).

**Explanation:**

Try it here.

```
s->{                                   // Method with String parameter and String return-type
  String r="",                         //  Result-String
    x="([AEIOU])",y="([BGNPRST])",     //  Two temp Strings for the validation-regex
    z="0O1I2R3E4A5S6G7T8B9P";          //  And a temp-String for the mapping
  for(int c:s.getBytes())              //  Loop over the characters of the input-String
    r+=                                //   Append to the result-String:
       c!=78&c!=85?                    //    If the character is not 'N' nor 'U':
        z.charAt(                      //     Get the character from the temp-String `z`
         (c=z.indexOf(c)+              //      by getting the character before or after the current character
            +(c<58?1:-1))              //      based on whether it's a digit or not
             <0?0:c)                   //      and a 0-check to prevent errors on incorrect input like '!@#'
       :                               //    Else:
        "";                            //     Append nothing
                                       //  End of loop (implicit / single-line body)
  return s.matches("(("+x+y+")*"+x+"?)|(("+y+x+")*"+y+"?)|\\d*")?
                                       //  If the input is valid
                                       //  (Only containing the vowels and consonants of `x` and `y`, without any adjacent ones. Or only containing digits)
    r                                  //   Return the result
     .replaceAll(x+"(?="+x+")","$1N")  //    after we've added 'N's if necessary
     .replaceAll(y+"(?="+y+")","$1U")  //    and 'U's if necessary
   :"";                                //  Or return an Empty String if invalid
}                                      // End of method

```

---

The validation regex:

```
(([AEIOU][BGNPRST])*[AEIOU]?)|(([BGNPRST][AEIOU])*[BGNPRST]?)|\\d*

```

# Answer
> 1 votes
# PHP; ~~129 127 267 259~~ 228 bytes

```
$l=IOREASGTBP;$n=1023456789;ctype_digit($s=$argn)?:$s=preg_replace("#U|N#","",strtr($o=$s,$l,$n));for($r=$c=($t=strtr($s,$n,$l))[$i++];$d=$t[$i++];)$r.=((trim($c,AEIO)xor$x=trim($d,AEIO))?X:UN[!$x]).$c=$d;echo$o?$o==$r?$s:"":$r;

```

Run as pipe with `-nR` or try it online.

**breakdown**

```
$l=IOREASGTBP;$n=1023456789;
# if not digits, translate letters to digits and remember original
ctype_digit($s=$argn)?:$s=preg_replace("#U|N#","",strtr($o=$s,$l,$n));
# translate digits to letters:
for($r=$c=($t=strtr($s,$n,$l))                      # result = first letter
    [$i++];$d=$t[$i++];)                            # loop through letters
    $r.=((trim($c,AEIO)xor$x=trim($d,AEIO))?"":UN[!$x]) # append delimiter if needed
        .$c=$d;                                         # append next letter
#
echo
    $o              # if original was remembered,
        ?$o==$r         # compare original to final result
            ?$s         # if equal, print digits
            :X          # else print X (as error message)
        :$r;        # else print letters

```

# Answer
> 1 votes
# sed, 123 bytes

```
s/[0134]/_&_/g
s/[25-9]/=&=/g
ta
y/OIREASGTBPU/0123456789N/
s/N//g
q
:a
s/__/N/g
s/==/U/g
y/0123456789_/OIREASGTBP=/
s/=//g

```

## Explanation

First, we surround digits with `_` (for vowels) or `=` (for consonants).

If we didn't make any substitutions, we are converting letters to digits, so it's a simple substitution, and delete `U` and `N`. Then quit.

Otherwise, we branch to label `a`, where we deal with consecutive vowels and then consecutive consonants. Then transform digits to letters, and delete the marker characters we introduced in the first step.

# Answer
> 1 votes
# Perl 5 `-p`, 155 bytes

```
$v="AEIO]";$c="RSGTBP]";$,=OIREASGTBP;eval"/[^0-9$,UN]|[^$v N|N[^$v|[^$c U|U[^$c|^[NU]|[NU]\$/x||y/0-9$,UN/$,0-9/d+s/[$v\\K(?=[$v)/N/g+s/[$c\\K(?=[$c)/U/g"

```

Try it online!

Recognizes some invalid inputs that the other Perl entry does not. Outputs the string unchanged if it is not valid.

# Answer
> 0 votes
# 05AB1E, 76 bytes

```
.•.Ÿ^91Ý•Ul„nuSKDXSKg0QVvXyk}JYP©0Êi®}¤«SXuèŒ2ùv…U NSy0èìžMuyåOè})Já¨¹d_iQ®P

```

Try it online!

Returns the falsy value `0` for invalid input.

# Answer
> 0 votes
# Bash, ~~241 238~~  235 bytes

```
q=OIREASGTBP;[[ $1 == +([0-9]) ]]&&(x=`tr 0-9 $q<<<$1`;m={B,G,P,R,S,T};n={A,E,I,O};for i in `eval echo $m$m$n$n`;{ a=${i::1};b=${i:1:1};x=${x//$a$b/$a'U'$b};a=${i:2:1};b=${i:3:1};x=${x//$a$b/$a'N'$b};};echo $x)||tr $q 0-9<<<$1|tr -d UN

```

Try it online!

Less golfed:

```
q=OIREASGTBP;                          save string in q
[[ $1 == +([0-9]) ]]&&(                if argument 1 is only digits
x=`tr 0-9 $q<<<$1`;                    save in x each digit translated to corresponding letter
m={B,G,P,R,S,T};
n={A,E,I,O};
for i in `eval echo $m$m$n$n`;{        generates all combinations of vowels and consonants
                                       BBAA BBAE ... TTOI TTOO
   a=${i::1};                          saves first consonant in a
   b=${i:1:1};                         saves second consonant in b
   x=${x//$a$b/$a'U'$b};               insets U between consonants
   a=${i:2:1};                         saves first vowel in a
   b=${i:3:1};                         saves second vowel in b
   x=${x//$a$b/$a'N'$b};               inserts N between vowels
};
echo $x                               echoes result
)||                                   if argument contains letters
  tr $q 0-9<<<$1|tr -d UN             translates letter to corresponding number and deletes U and N

```

# Answer
> 0 votes
# PHP, 268 Bytes

```
$v=OIEA;$l=RSGTBP;$d="0134256789";$c=ctype_digit;$p=preg_replace;echo!$c($a=$argn)?$c($e=strtr($p(["#\d|[$v]{2,}|[$l]{2,}#","#[$v]\KN(?=[$v])#","#[$l]\KU(?=[$l])#"],[_,"",""],$a),$v.$l,$d))?$e:_:$p(["#[$v](?=[$v])#","#[$l](?=[$l])#"],["$0N","$0U"],strtr($a,$d,$v.$l));

```

Try it online!

# Answer
> 0 votes
# Ruby, 205+1 = 206 bytes

Uses the `-p` flag for +1 byte. Now with an exhaustive input validation system.

```
d,w=%w"0-9 OIREASGTBP"
~/^\d+$/?($_.tr!d,w
gsub /([#{a='AEIO])(?=\g<1>)'}/,'\0N'
gsub /([^#{a}/,'\0U'):(+~/^(([AEIO])(N(?=[AEIO])|(?=\g<4>)|$)|([RSGTBP])(U(?=\g<4>)|(?=\g<2>|$)))+$/;$_.tr!("NU","").tr!w,d)

```

Try it online!

# Answer
> 0 votes
# Perl, 127 bytes

126 bytes + 1 byte command line

```
$i="AEIOU]";$;=OIREASGTBP;1/!/[^$;NU\d]|[$i{2}|[^\d$i{2}/;eval"y/0-9$;NU/$;0-9/d";s/[$i\K(?=[$i)/N/g;s/[^N\d$i\K(?=[^\d$i)/U/g

```

Usage:

```
 echo -n "512431" | perl -p entry.pl

```

Should follow all the challenge rules - can accept letters or numbers and will error (division by zero) if validation fails

# Answer
> 0 votes
# Python 3, 741 bytes

```
from functools import reduce;c=0;e="";n="NU";v="AEIOU";l="OIREASGTBPNU";x=('0','O'),('1','I'),('2','R'),('3','E'),('4','A'),('5','S'),('6','G'),('7','T'),('8','B'),('9','P');s=input()
try:
    int(s);y=reduce(lambda a,kv:a.replace(*kv),x,s)
    for i in y:
        e+=i
        if i in v:
            z=True
            try:
                if y[c+1] in v:e+="N"
            except:
                pass
        else:
            z=False
            try:
                if not y[c+1] in v:e+="U"
            except:
                pass
        c+=1
except:
    for i in s:
        if not i in l:
            p
    y=reduce(lambda a,kv:a.replace(*kv[::-1]),x,s)
    for i in y:
        if not i in n:e+=i
print(e)

```

Try it online!

There's a lot of room for improvement, I know.

# Answer
> 0 votes
## Python3, 246 bytes

```
v=lambda x:x in"AEIO"
V="OIREASGTBP"
i=input()
r=__import__("functools").reduce
print(r(lambda x,y:x+(("U",""),("","N"))[v(x[-1])][v(y)]+y,map(lambda x:V[x],map(int,i)))if i.isdigit()else r(lambda x,y:x*10+V.index(y),filter(lambda x:x in V,i),0))

```

explanation:

* map input to a list of int
* map list of int to their position in the alphabet
* reduce list by adding accumulator, plus an element of a ~~dict~~tuple, plus the current element
    + the ~~dict~~tuple is a truth table based on two elements, being vowel or not

# Answer
> 0 votes
# JavaScript (ES6), 120

A function taking input as a string. It returns the properly translated string if the input is valid, else false or the function crashes.

```
n=>(t=n=>n.replace(/./g,d=>1/d?(v-(v=d<5&d!=2)?'':'UN'[v])+z[d]:~(a=z.search(d))?a:'',v=2,z='OIREASGTBP'))(q=t(n))==n&&q

```

*Less golfed*

```
n =>
{
  var t = n => { // function to translate, no check for invalid input
    var v = 2; // 1 = digit map to vowel, 0 = digit map to consonant, start with 2
    var z = 'OIREASGTBP'; // digits mapping
    return n.replace(/./g,
      d => 1/d // digit / alpha check
        ? ( // if digit
            w = v, // save previous value of v
            v = d < 5 & d != 2, // check if current digit will map to wovel or consonant
            (w != v
             ? '' // if different - wovel+consonant or consonant+wovel or start of input
             : 'UN'[v] // if equal, insert required separator
            ) + z[d] // add digit translation
          )
        : ( // if alpha
             a = z.search(d), // look for original digit. Could crash if d is a reserved regexp char (not valid input)
             a != -1 ? a : '' // if digit found add to output, else do nothing
          )
    )
  }

  var q = t(n); // translate input an put in q
  if (t(q) == n) // translate again, result must be == to original input
    return q; // if ok return result
  else
    return false; // else return false
}

```

**Test**

```
var F=
n=>(t=n=>n.replace(/./g,d=>1/d?(v-(v=d<5&d!=2)?'':'UN'[v])+z[d]:~(a=z.search(d))?a:'',v=2,z='OIREASGTBP'))(q=t(n))==n&&q

;`512431 => SIRANENI
834677081 => BENAGUTUTOBI
3141592 => ENINANISUPUR
1234567890 => IRENASUGUTUBUPO
6164817 => GIGABIT`
.split('\n')
.forEach(x => {
  var [a,b] = x.match(/\w+/g)
  var ta = F(a)
  var tb = F(b)
  console.log(a==tb ? 'OK':'KO', a + ' => '+ ta)
  console.log(b==ta ? 'OK':'KO', b + ' => '+ tb)
})

function go() {
  O.textContent = F(I.value)
}

go()
```

```
<input id=I value='NUNS' oninput='go()'>
<pre id=O></pre>
```

# Answer
> 0 votes
# APL (Dyalog Unicode), 71 bytes

```
' '~⍨,({' ',2{∧/x←'AEIOU'∊⍨⍺⍵:'N'⋄∧/~x:'U'⋄' '}/⍵},⍪)'OIREASGTBP'[⍎¨⍕⎕]

```

Try it online!

This turned out surprisingly short!

Uses `⎕IO←0` (0-indexing).

## Explanation

```
' '~⍨,({' ',2{∧/x←'AEIOU'∊⍨⍺⍵:'N'⋄∧/~x:'U'⋄' '}/⍵},⍪)'OIREASGTBP'[⍎¨⍕⎕]
                                                                  ⍎¨⍕⎕  get the digits of the input
                                                     'OIREASGTBP'[    ] map to the correct letters
      {' ',2{∧/x←'AEIOU'∊⍨⍺⍵:'N'⋄∧/~x:'U'⋄' '}/⍵},⍪                     join the following with the tabled argument:
                                              /⍵                        map pairs of the argument to:
           2 ∧/x←'AEIOU'∊⍨⍺⍵:'N'                                        N if vowel pair,
                                ⋄∧/~x:'U'                               U if consonant pair,
                                         ⋄' '                           space otheriwse.
       ' ',                                                             prepend a space
    ,                                                                   flatten the result
' '~⍨                                                                   remove all spaces

```

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


title: Is it a Harshad Number?

text:
# Question
Title: Is it a Harshad Number?
A Harshad number is a number that is divisible by the sum of its digits. This is obviously dependent on what base the integer is written in. Base 10 Harshad numbers are sequence A005349 in the OEIS.

## Your Task:

Write a program or function that determines whether a given integer is a Harshad number in a given base.

## Input:

A positive integer \<10^9, and a base between 2 and 36, OR, a positive integer in its base, using lowercase letters for the numbers from 11-36 and a base between 2 and 36. You only have to handle one of these options.

## Output:

A truthy/falsy value indicating whether the first input is a Harshad number in the base of the second input.

## Examples:

```
27,10 ----------> truthy
8,5 ------------> truthy
9,5 ------------> falsy
1a,12 OR 22,12 -> truthy

```

## Scoring:

This is , lowest score in bytes wins.

# Answer
# Jelly, 4 bytes

```
bSḍḷ

```

Try it online!

### How it works

```
bSḍḷ  Main link. Arguments: n (integer), k (base)

b     Convert n to base k.
 S    Take the sum.
   ḷ  Left; yield n.
  ḍ   Test for divisibility.

```
> 11 votes

# Answer
# Python 2, 46 bytes

```
lambda n,b:n%sum(n/b**i%b for i in range(n))<1

```

Try it online!
> 12 votes

# Answer
# Python 3, 73 bytes

```
def f(n,b):
 if b<2:return 1
 s=0;c=n
 while n:s+=n%b;n//=b
 return c%s<1

```

Try it online!

1 is truthy, you know.
> 4 votes

# Answer
# Python 2, ~~54~~ 47 bytes

```
n,k=input();m=n;s=0
exec's-=m%k;m/=k;'*n
1>>n%s

```

Time and memory complexity are **O(n)**, so don't try **109** on TIO.

Output is via exit code, so **0** is truthy, **1** is falsy. If this output method winds up being allowed, a further byte can be saved by turning the program into a function.

*Thanks to @musicman523 for suggesting exit codes!*

Try it online!
> 4 votes

# Answer
# Pyth, 12 7 bytes

```
!%hQsjF

```

Try it online!

Byte count is now lower since unary is no longer required.

### Explanation

```
!%hQsjF
     jF    Fold the input over base conversion (converts given number to given base)
    s      Sum the values
  %hQ       Take the first input modulo that sum
!          Logical not, turning 0s from the modulus into True and all else into False

```
> 3 votes

# Answer
# Dyalog APL, 20 bytes

```
{⍺=1:0⋄⍵|⍨+/⍺⊥⍣¯1⊢⍵}

```

Try it online! \[15 first numbers in 15 first bases\]

Takes the number as a right argument and the base as a left argument, 0 is truthy.

**How?**

`⍺⊥⍣¯1⊢⍵` \-  in base  as a list of digits

`⍵|⍨` \-  modulo ...

`+/` \- the sum
> 3 votes

# Answer
# Husk, 5 bytes

```
¦ΣB²¹

```

Try it online!
> 3 votes

# Answer
# , ~~64~~ 60 bytes

(requires the `pryr` package)

```
pryr::f({d=pryr::f('if'(n<b,n,n%%b+d(b,n%/%b)));!n%%d(b,n)})

```

This is an anonymous function that takes two arguments, `b` and `n` that evaluates to (which is on TIO):

```
function(b,n){
   d=function(b,n)
     if(n<b) n else n%%b + d(b,n%/%b)
   !n%%d(b,n)
}

```

where `d` computes the digit sum for the required base.

Dropped 4 bytes once the base was guaranteed to be greater than 1.

Try it online!
> 2 votes

# Answer
# Japt, 9 bytes

```
vUsV ¬xnV

```

Takes input as two integers.

Try it online!
> 2 votes

# Answer
## Javascript (ES6), ~~68~~ 67 bytes

```
n=>k=>!(n%eval([...n.toString(k)].map(_=>parseInt(_,k)).join('+')))

```

Note that since we are required only to handle either base-*k* or base-10 numbers for `n`, I assume `n` is a base-10 integer always.

-1 byte, thanks to TheLethalCoder!

How it works:

```
!                                    # Convert to true if 0 else false
 (n%                                 # Compute n modulo
    eval(                            # evaluate string
         [...n.toString(k)]          # convert to array of base-k divisors
         .map(_=>parseInt(_,k))      # map lowercase characters to ints
         .join('+')                  # join array as string of characters
    )                                # get the raw remainder, and let ! do its work
 )

```

Try it online!
> 2 votes

# Answer
# Java (OpenJDK 8), 54 bytes

```
n->b->{int s=0,c=n;for(;c>0;c/=b)s+=c%b;return n%s<1;}

```

Try it online!
> 2 votes

# Answer
# K (ngn/k), 12 bytes

```
{~(+/y\x)!x}

```

Try it online!

A function taking an integer (`x`) and the base to use (`y`).

* `y\x` convert `x` to a base-`y` representation
* `+/` take the sum of the digits
* `~(...)!x` check if the sum of the digits mod the input integer is non-zero
> 2 votes

# Answer
# Javascript ES6, 62 bytes

```
n=>b=>!(n%[...n.toString(b)].reduce((x,y)=>x+parseInt(x,b),0))

```
> 1 votes

# Answer
# C (gcc), 37 bytes

```
f(n,b,i,s){n?f(n/b,b,i,s+n%b):i%s<1;}

```

Try it online!

Returns zero for true, non-zero for false.
I want to know, why not just `i%s` does work, but `i%s<1` does (*isn't that very strange?*).
> 1 votes

# Answer
# Perl 6, 40 bytes

```
{$^b>1??$^a%%[+] $a.polymod($b xx*)!!?1}

```

Test it

## Expanded:

```
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣

    $^b > 1          # declare ｢$b｣ and compare against 1

  ??                 # if ｢$b > 1｣ then:

      $^a            # declare ｢$a｣
    %%               # is it divisible by
      [+]            # reduce the following with &infix:<+> (sum)
        $a.polymod(
          $b xx *    # infinite list of ｢$b｣s
        )

  !!                 # if ｢$b <= 1｣ then:

    ? 1              # Boolify 1 (shorter than True)
}

```
> 0 votes

# Answer
# Mathematica, 30 bytes

```
#2<2||Tr@IntegerDigits@##∣#&

```

Pure function taking two arguments, the integer and the base (in that order), and returning `True` or `False`. Careful: the first two `|`s are just the normal ASCII character, while the last  is U+2223.

`#2<2` deals with the special case of base 1. Otherwise, `Tr@IntegerDigits@##` produces the sum of the digits of the first argument when written in the base of the second argument, and `...∣#` tests whether that sum divides the first argument.
> 0 votes

# Answer
## Batch, 119 bytes

```
@if %2==1 echo 1&exit/b
@set/at=%1,s=0
:l
@if %t% gtr 0 set/as+=t%%%2,t/=%2&goto l
@set/at=%1%%s
@if %t%==0 echo 1

```

Outputs 1 for Harshad numbers.
> 0 votes

# Answer
# Python 3, 45 bytes

```
lambda n,b:int(n,b)%sum(int(i,b)for i in n)<1

```

Try it online!

Based on the updated formats for input.
> 0 votes

# Answer
# C (gcc), 57 bytes

```
f(n,b,t,s){while(b>1&&t){s+=t%b;t/=b;}return b<2||n%s<1;}

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 25 bytes

```
(n,b)->n%sumdigits(n,b)<1

```

Try it online!
> 0 votes

# Answer
# Japt `-!`, 5 bytes

```
%ìV x

```

Try it
> 0 votes

# Answer
# C (gcc), ~~49~~ 43 bytes

```
a,b;f(x,n){for(a=x,b=0;b+=x%n,x/=n;);a%=b;}

```

Try it online!

Returns zero for true, non-zero for false.

It is very simple. It just accumulates all the digits of `x` in `b` and returns `x % b`.

Ungolfed version:

```
// local variables
int a, b;
int f(int x, int n)
{
    // Accumulate all digits in b
    // Note that the for loop only checks x /= n
    for (a = x, b = 0; b += x % n, x /= n;)
        ;
    // Then return a % b.
    return a % b;
}

```

Thanks to dingledooper for the -6 bytes!
> 0 votes

# Answer
# x86 Machine Code, 19 bytes

```
50 31 C9 99 F7 F6 01 D1 85 C0 75 F7 58 99 F7 F1 85 D2 C3

```

The above bytes define a function that accepts the value in the `EAX` register and the base in the `ESI` register, and sets the zero flag (`ZF`) based on whether the value is a Harshad number (`ZF` will be clear if the value is a Harshad number).

Note that this is a custom calling convention, defined expressly for the purposes of this challenge. Assembly/machine language programmers are allowed to do that. However, note further that the choice of the `ESI` register for the second parameter (base) is completely arbitrary. This can be changed to any other unused general-purpose integer register (*i.e.*, `EBX`, `EDI`, or `EBP`) without affecting either correctness or code size.

**Try it online!**

In ungolfed assembly language mnemonics:

; bool IsHarshadNumber(unsigned value, unsigned base)
;
; Inputs:
;    EAX = input value
;    ESI = base
; Outputs:
;    ZF = 0 if Harshad number; otherwise, ZF = 1
; Clobbers:
;    EAX, EDX, ECX
;
        IsHarshadNumber:
50         push   eax             ; preserve input value
31 C9      xor    ecx, ecx        ; zero-out accumulator

        Accumulate:               ; <----------------------------------------------------\
99         cdq                    ; zero-out EDX (based on EAX) to prepare for division  |
F7 F6      div    esi             ; divide by base (EAX = quotient; EDX = remainder)     |
01 D1      add    ecx, edx        ; accumulate remainder                                 |
85 C0      test   eax, eax        ; is quotient 0?                                       |
75 F7      jnz    Accumulate      ; keep looping until it is ----------------------------/

58         pop    eax             ; restore input value
99         cdq                    ; zero-out EDX (based on EAX) to prepare for division
F7 F1      div    ecx             ; divide by accumulator
85 D2      test   edx, edx        ; set ZF based on remainder
C3         ret
```
</code></pre>
> 0 votes

# Answer
# Ruby, 43 bytes

```
->n,b,s=0,i=n{(s+=n%b;n/=b)while n>0;i%s<1}

```

Try it online!

---

# Ruby, 43 bytes

```
f=->n,b,s=0,i=n{n>0?f[n/b,b,s+n%b,i]:i%s<1}

```

Try it online!
> 0 votes

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

```
f=(n,b,s=0,i=n)=>n?f(n/b|0,b,s+n%b,i):i%s

```

Try it online!

Returns zero for true, non-zero for false.
> 0 votes

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


title: Find the closest Fibonacci Number

text:
# Question
Title: Find the closest Fibonacci Number
We are all familiar with the famous Fibonacci sequence, that starts with `0` and `1`, and each element is the sum of the previous two. Here are the first few terms (OEIS A000045):

```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584

```

---

Given a *positive integer*, return the closest number of the Fibonacci sequence, under these rules:

* The *closest Fibonacci number* is defined as the Fibonacci number with the smallest absolute difference with the given integer. For example, `34` is the closest Fibonacci number to `30`, because `|34 - 30| = 4`, which is smaller than the second closest one, `21`, for which `|21 - 30| = 9`.
* If the given integer belongs to the Fibonacci sequence, the closest Fibonacci number is exactly itself. For example, the closest Fibonacci number to `13` is exactly `13`.
* In case of a tie, you may choose to output either one of the Fibonacci numbers that are both closest to the input or just output them both. For instance, if the input is `17`, all of the following are valid: `21`, `13` or `21, 13`. In case you return them both, please mention the format.

Default Loopholes apply. You can take input and provide output through any standard method. Your program / function must only handle values up to 108.

---

# Test Cases

```
Input -> Output

1    -> 1
3    -> 3
4    -> 3 or 5 or 3, 5
6    -> 5
7    -> 8
11   -> 13
17   -> 13 or 21 or 13, 21
63   -> 55
101  -> 89
377  -> 377
467  -> 377
500  -> 610
1399 -> 1597

```

---

# Scoring

This is , so the shortest code in bytes *in every language* wins!

# Answer
# Python 2, 43 bytes

```
f=lambda n,a=0,b=1:a*(2*n<a+b)or f(n,b,a+b)

```

Try it online!

Iterates through pairs of consecutive Fibonacci numbers `(a,b)` until it reaches one where the input `n` is less than their midpoint `(a+b)/2`, then returns `a`.

Written as a program (47 bytes):

```
n=input()
a=b=1
while 2*n>a+b:a,b=b,a+b
print a

```

Same length:

```
f=lambda n,a=0,b=1:b/2/n*(b-a)or f(n,b,a+b)

```
> 20 votes

# Answer
# Neim, 5 bytes

```
fS

```

Explanation:

```
f       Push infinite Fibonacci list
                      93
       Select the first ^ elements
        This is the maximum amount of elements we can get before the values overflow
        which means the largest value we support is 7,540,113,804,746,346,429
   S   Closest value to the input in the list

```

In the newest version of Neim, this can be golfed to 3 bytes:

```
fS

```

As infinite lists have been reworked to only go up to their maximum value.

Try it online!
> 14 votes

# Answer
# Python, ~~55~~ 52 bytes

```
f=lambda x,a=1,b=1:[a,b][b-x<x-a]*(b>x)or f(x,b,a+b)

```

Try it online!
> 10 votes

# Answer
# , ~~70~~ ~~67~~ ~~64~~ ~~62~~ 60 bytes

*-2 bytes thanks to djhurio!*

*-2 more bytes thanks to djhurio* (boy can he golf!)

```
F=1:0;while(F<1e8)F=c(F[1]+F[2],F);F[order((F-scan())^2)][1]

```

Since we only have to handle values up to `10^8`, this works.

Try it online!

Reads `n` from stdin. the `while` loop generates the fibonacci numbers in `F` (in decreasing order); in the event of a tie, the larger is returned. This will trigger a number of warnings because `while(F<1e8)` only evaluates the statement for the first element of `F` with a warning

Originally I used `F[which.min(abs(F-n))]`, the naive approach, but @djhurio suggested `(F-n)^2` since the ordering will be equivalent, and `order` instead of `which.min`. `order` returns a permutation of indices to put its input into increasing order, though, so we need `[1]` at the end to get only the first value.

### faster version:

```
F=1:0;n=scan();while(n>F)F=c(sum(F),F[1]);F[order((F-n)^2)][1]

```

only stores the last two fibonacci numbers
> 9 votes

# Answer
# Jelly, ~~9~~ 7 bytes

-2 bytes thanks to @EriktheOutgolfer

```
‘RÆḞạÐṂ

```

Try it online!

Golfing tips welcome :). Takes an int for input and returns an int-list.

```
            ' input -> 4
‘           ' increment -> 5
 R          ' range -> [1,2,3,4,5]
  ÆḞ        ' fibonacci (vectorizes) -> [1,1,2,3,5,8]
     ÐṂ     ' filter and keep the minimum by:
    ạ       ' absolute difference -> [3,3,2,1,1,4]
            ' after filter -> [3,5]

```
> 6 votes

# Answer
## JavaScript (ES6), 41 bytes

```
f=(n,x=0,y=1)=>y<n?f(n,y,x+y):y-n>n-x?x:y
```

```
<input type=number min=0 value=0 oninput=o.textContent=f(this.value)><pre id=o>0
```

Rounds up by preference.
> 6 votes

# Answer
# Mathematica, 30 bytes

```
Array[Fibonacci,2#]~Nearest~#&

```

Try it online!
> 5 votes

# Answer
# x86-64 Machine Code, 24 bytes

```
31 C0 8D 50 01 92 01 C2 39 FA 7E F9 89 D1 29 FA 29 C7 39 D7 0F 4F C1 C3

```

The above bytes of code define a function in 64-bit x86 machine code that finds the closest Fibonacci number to the specified input value, `n`.

The function follows the System V AMD64 calling convention (standard on Gnu/Unix systems), such that the sole parameter (`n`) is passed in the `EDI` register, and the result is returned in the `EAX` register.

**Ungolfed assembly mnemonics:**

```
; unsigned int ClosestFibonacci(unsigned int n);
    xor    eax, eax        ; initialize EAX to 0
    lea    edx, [rax+1]    ; initialize EDX to 1

  CalcFib:
    xchg   eax, edx        ; swap EAX and EDX
    add    edx, eax        ; EDX += EAX
    cmp    edx, edi
    jle    CalcFib         ; keep looping until we find a Fibonacci number > n

    mov    ecx, edx        ; temporary copy of EDX, because we 'bout to clobber it
    sub    edx, edi
    sub    edi, eax
    cmp    edi, edx
    cmovg  eax, ecx        ; EAX = (n-EAX > EDX-n) ? EDX : EAX
    ret

```

**Try it online!**

The code basically divides up into three parts:

* The first part is very simple: it just initializes our working registers. `EAX` is set to 0, and `EDX` is set to 1.
* The next part is a loop that iteratively calculates the Fibonacci numbers on either side of the input value, `n`. This code is based on my previous implementation of Fibonacci with subtraction, but…um…isn't with subtraction. :-) In particular, it uses the same trick of calculating the Fibonacci number using two variables—here, these are the `EAX` and `EDX` registers. This approach is *extremely* convenient here, because it gives us adjacent Fibonacci numbers. The candidate potentially *less than* `n` is held in `EAX`, while the candidate potentially *greater than* `n` is held in `EDX`. I'm quite proud of how tight I was able to make the code inside of this loop (and even more tickled that I re-discovered it independently, and only later realized how similar it was to the subtraction answer linked above).
* Once we have the candidate Fibonacci values available in `EAX` and `EDX`, it is a conceptually simple matter of figuring out which one is closer (in terms of absolute value) to `n`. Actually taking an absolute value would cost *way* too many bytes, so we just do a series of subtractions. The comment out to the right of the penultimate conditional-move instruction aptly explains the logic here. This either moves `EDX` into `EAX`, or leaves `EAX` alone, so that when the function `RET`urns, the closest Fibonacci number is returned in `EAX`.

In the case of a tie, the *smaller* of the two candidate values is returned, since we've used `CMOVG` instead of `CMOVGE` to do the selection. It is a trivial change, if you'd prefer the other behavior. Returning *both* values is a non-starter, though; only one integer result, please!
> 5 votes

# Answer
# PowerShell, ~~80~~ 74 bytes

```
param($n)for($a,$b=1,0;$a-lt$n;$a,$b=$b,($a+$b)){}($b,$a)[($b-$n-gt$n-$a)]

```

(Try it online! temporarily unresponsive)

Iterative solution. Takes input `$n`, sets `$a,$b` to be `1,0`, and then loops with Fibonacci until `$a` is larger than the input. At that point, we index into `($b,$a)` based on Boolean of whether the difference between the first element and `$n` is greater than between `$n` and the second element. That's left on the pipeline, output is implicit.
> 4 votes

# Answer
## JavaScript (ES6), 67 bytes

```
f=(n,k,y)=>(g=k=>x=k>1?g(--k)+g(--k):k)(k)>n?x+y>2*n?y:x:f(n,-~k,x)

```

### Test cases

```
f=(n,k,y)=>(g=k=>x=k>1?g(--k)+g(--k):k)(k)>n?x+y>2*n?y:x:f(n,-~k,x)

console.log(f(1   )) // -> 1
console.log(f(3   )) // -> 3
console.log(f(4   )) // -> 3 or 5 or 3, 5
console.log(f(6   )) // -> 5
console.log(f(7   )) // -> 8
console.log(f(11  )) // -> 13
console.log(f(17  )) // -> 13 or 21 or 13, 21
console.log(f(63  )) // -> 55
console.log(f(101 )) // -> 89
console.log(f(377 )) // -> 377
console.log(f(467 )) // -> 377
console.log(f(500 )) // -> 610
console.log(f(1399)) // -> 1597
```
> 4 votes

# Answer
# JavaScript (Babel Node), 41 bytes

```
f=(n,i=1,j=1)=>j<n?f(n,j,j+i):j-n>n-i?i:j

```

Based on ovs's awesome Python answer

Try it online!

### Ungolfed

```
f=(n,i=1,j=1)=> // Function f: n is the input, i and j are the most recent two Fibonacci numbers, initially 1, 1
 j<n?           // If j is still less than n
  f(n,j,j+i)    //  Try again with the next two Fibonacci numbers
 :              // Else:
  j-n>n-i?i:j   //  If n is closer to i, return i, else return j

```
> 4 votes

# Answer
# Python, 74 bytes

```
import math
r=5**.5
p=r/2+.5
lambda n:round(p**int(math.log(n*2*r,p)-1)/r)

```

Try it online!

### How it works

For all *k* ≥ 0, since |φ*k*/√5| \< 1/2, *F**k* = φ*k*/√5 + φ*k*/√5 = round(φ*k*/√5). So the return value switches from *F**k* − 1 to *F**k* exactly where *k* = logφ(*n*⋅2√5) − 1, or *n* = φ*k* \+ 1/(2√5), which is within 1/4 of *F**k* \+ 1/2 = (*F**k* − 1 \+ *F**k*)/2.
> 4 votes

# Answer
# 05AB1E, 6 bytes

```
nÅFs.x

```

Try it online!
> 3 votes

# Answer
# Python 3, 103 bytes

```
import math
def f(n):d=5**.5;p=.5+d/2;l=p**int(math.log(d*n,p))/d;L=[l,p*l];return round(L[2*n>sum(L)])

```

Try it online!

Sadly, had to use a def instead of lambda... There's probably much room for improvement here.

Original (incorrect) answer:

# ~~Python 3, 72 bytes~~

```
lambda n:r(p**r(math.log(d*n,p))/d)
import math
d=5**.5
p=.5+d/2
r=round

```

Try it online!

My first PPCG submission. Instead of either calculating Fibonacci numbers recursively or having them predefined, this code uses how the n-th Fibonacci number is the nearest integer to the n-th power of the golden ratio divided by the root of 5.
> 3 votes

# Answer
# C (gcc), ~~86~~ ~~85~~ ~~83~~ 76 bytes

```
f(n){n=n<2?:f(n-1)+f(n-2);}i,j,k;g(n){for(;k<n;j=k,k=f(i++));n=k-n<n-j?k:j;}

```

Try it online!
> 3 votes

# Answer
# Java (OpenJDK 8), ~~60~~ ~~57~~ 56 bytes

```
c->{int s=1,r=2;for(;c>r;s=r-s)r+=s;return c-s>r-c?r:s;}

```

Try it online!

-1 byte thanks to @Neil
> 3 votes

# Answer
# Taxi, 2321 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:n 1 l 1 l.0 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 l.Pickup a passenger going to Bird's Bench.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.[a]Pickup a passenger going to Rob's Rest.Pickup a passenger going to Magic Eight.Go to Bird's Bench:n 1 r 2 r 1 l.Go to Rob's Rest:n.Go to Trunkers:s 1 l 1 l 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:w 2 r.Pickup a passenger going to Trunkers.Pickup a passenger going to Magic Eight.Go to Zoom Zoom:n.Go to Trunkers:w 3 l.Go to Magic Eight:e 1 r.Switch to plan "b" if no one is waiting.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:w 1 r.Go to Rob's Rest:w 1 l 1 r 1 l 1 r 1 r.Pickup a passenger going to Cyclone.Go to Bird's Bench:s.Pickup a passenger going to Addition Alley.Go to Cyclone:n 1 r 1 l 2 l.Pickup a passenger going to Addition Alley.Pickup a passenger going to Bird's Bench.Go to Addition Alley:n 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Switch to plan "a".[b]Go to Trunkers:w 1 l.Pickup a passenger going to Cyclone.Go to Bird's Bench:w 1 l 1 r 1 l.Pickup a passenger going to Cyclone.Go to Rob's Rest:n.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 l.Pickup a passenger going to Magic Eight.Go to Sunny Skies Park:e 1 r 1 l.Go to Cyclone:n 1 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to What's The Difference.Go to Sunny Skies Park:n 1 r.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 1 r 1 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:e 1 r 2 l 2 r.Switch to plan "c" if no one is waiting.Go to Sunny Skies Park:w 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to Cyclone:n 1 l.Switch to plan "d".[c]Go to Cyclone:w 1 l 2 r.[d]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 2 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

```

Try it online!
Try it online with comments!

Un-golfed with comments:

```
[ Find the Fibonacci number closest to the input ]
[ Inspired by: https://codegolf.stackexchange.com/q/133365 ]

[ n = STDIN ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Trunkers.
Go to Trunkers: north 1st left 1st left.

[ Initialize with F0=0 and F1=1 ]
0 is waiting at Starchild Numerology.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 2nd left.
Pickup a passenger going to Bird's Bench.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 1st right 4th left.

[ For (i = 1; n > F(i); i++) { Store F(i) at Rob's Rest and F(i-1) at Bird's Bench } ]
[a]
Pickup a passenger going to Rob's Rest.
Pickup a passenger going to Magic Eight.
Go to Bird's Bench: north 1st right 2nd right 1st left.
Go to Rob's Rest: north.
Go to Trunkers: south 1st left 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Trunkers.
Pickup a passenger going to Magic Eight.
Go to Zoom Zoom: north.
Go to Trunkers: west 3rd left.
Go to Magic Eight: east 1st right.
Switch to plan "b" if no one is waiting.

[ n >= F(i) so iterate i ]
Pickup a passenger going to Firemouth Grill.
Go to Firemouth Grill: west 1st right.
Go to Rob's Rest: west 1st left 1st right 1st left 1st right 1st right.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: south.
Pickup a passenger going to Addition Alley.
Go to Cyclone: north 1st right 1st left 2nd left.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Bird's Bench.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left 1st left.
Switch to plan "a".

[b]
[ F(i) > n which means n >= F(i-1) and we need to figure out which is closer and print it]
Go to Trunkers: west 1st left.
Pickup a passenger going to Cyclone.
Go to Bird's Bench: west 1st left 1st right 1st left.
Pickup a passenger going to Cyclone.
Go to Rob's Rest: north.
Pickup a passenger going to Cyclone.
Go to Cyclone: south 1st left 1st left 2nd left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to What's The Difference.
[ Passengers:n, n, F(i-1) ]
Go to What's The Difference: north 1st left.
Pickup a passenger going to Magic Eight.
[ Passengers:n, n-F(i-1) ]
Go to Sunny Skies Park: east 1st right 1st left.
Go to Cyclone: north 1st left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to What's The Difference.
[ Passengers: n-F(i-1), F(i-1), F(i) ]
Go to Sunny Skies Park: north 1st right.
Pickup a passenger going to What's The Difference.
[ Passengers: n-F(i-1), F(i), n ]
Go to What's The Difference: north 1st right 1st left.
[ Passengers: n-F(i-1), F(i)-n ]
Pickup a passenger going to Magic Eight.
Go to Magic Eight: east 1st right 2nd left 2nd right.
Switch to plan "c" if no one is waiting.

[ If no one was waiting, then {n-F(i-1)} < {F(i)-n} so we return F(i-1) ]
Go to Sunny Skies Park: west 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to Cyclone: north 1st left.
Switch to plan "d".

[c]
[ Otherwise {n-F(i-1)} >= {F(i)-n} so we return F(i) ]
[ Note: If we didn't switch to plan c, we still pickup F(i) but F(i-1) will be the *first* passenger and we only pickup one at The Babelfishery ]
[ Note: Because of how Magic Eight works, we will always return F(i) in the event of a tie ]
Go to Cyclone: west 1st left 2nd right.
[d]
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 2nd right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

```
> 3 votes

# Answer
# Python 3, 84 bytes

```
lambda k:min(map(f,range(2*k)),key=lambda n:abs(n-k))
f=lambda i:i<3or f(i-1)+f(i-2)

```

Try it online!

It may work, but it's certainly not fast...

Outputs `True` instead of `1`, but in Python these are equivalent.
> 2 votes

# Answer
# dc, 52 bytes

```
si1d[dsf+lfrdli>F]dsFxli-rlir-sdd[lild-pq]sDld<Dli+p

```

Try it online!

Takes input at run using `?`

Edited to assume top of stack as input value, -1 byte.

Input is stored in register `i`. Then we put 1 and 1 on the stack to start the Fibonacci sequence, and we generate the sequence until we hit a value greater than `i`. At this point we have two numbers in the Fibonacci sequence on the stack: one that is less than or equal to `i`, and one that is greater than `i`. We convert these into their respective differences with `i` and then compare the differences. Finally we reconstruct the Fibonacci number by either adding or subtracting the difference to `i`.

Oops, I was loading two registers in the wrong order and then swapping them, wasting a byte.
> 2 votes

# Answer
# C# (.NET Core), 63 56 bytes

-1 byte thanks to @Neil

-6 bytes thanks to @Nevay

```
n=>{int a=0,b=1;for(;b<n;a=b-a)b+=a;return n-a>b-n?b:a;}

```

Try it online!
> 2 votes

# Answer
## Q/KDB+, 51 bytes

```
{w where l=min l:abs neg[x]+w:{x,sum -2#x}/[x;0 1]}

```
> 2 votes

# Answer
# Hexagony, 37 bytes

```
?\=-${&"*.2}+".|'=='.@.&}1.!_|._}$_}{

```

Try it online!

ungolfed:

```
   ? \ = -
  $ { & " *
 . 2 } + " .
| ' = = ' . @
 . & } 1 . !
  _ | . _ }
   $ _ } {

```

Broken down:

```
start:
? { 2 ' * //set up 2*target number
" ' 1     //initialize curr to 1

main loop:
} = +     //next + curr + last
" -       //test = next - (2*target)
branch: <= 0 -> continue; > 0 -> return

continue:
{ } = &   //last = curr
} = &     //curr = next

return:
{ } ! @   //print last

```

Like some other posters, I realized that when the midpoint of last and curr is greater than the target, the smaller of the two is the closest or tied for closest.

The midpoint is at (last + curr)/2. We can shorten that because next is already last + curr, and if we instead multiply our target integer by 2, we only need to check that (next - 2\*target) \> 0, then return last.
> 2 votes

# Answer
# Brachylog, 22 bytes

```
;I≜-.∧{0;1⟨t≡+⟩ⁱhℕ↙.!}

```

Try it online!

Really all I've done here is paste together Fatalize's classic Return the closest prime number solution and my own Am I a Fibonacci Number? solution. Fortunately, the latter already operates on the output variable; unfortunately, it also includes a necessary cut which has to be isolated for +2 bytes, so the only choice point it discards is , leaving  intact.
> 2 votes

# Answer
# Japt `-g`, 8 bytes

```
ò!gM ñaU

```

Try it
> 2 votes

# Answer
# Java 7, ~~244~~ 234 Bytes

```
 String c(int c){for(int i=1;;i++){int r=f(i);int s=f(i-1);if(r>c && s<c){if(c-s == r-c)return ""+r+","+s;else if(s-c > r-c)return ""+r;return ""+s;}}} int f(int i){if(i<1)return 0;else if(i==1)return 1;else return f(i-2)+f(i-1);}

```
> 1 votes

# Answer
# Pyke, 6 bytes

```
}~F>R^

```

Try it online!

```
}      -    input*2
 ~F    -   infinite list of the fibonacci numbers
   >   -  ^[:input]
    R^ - closest_to(^, input)

```
> 1 votes

# Answer
# Common Lisp, 69 bytes

```
(lambda(n)(do((x 0 y)(y 1(+ x y)))((< n y)(if(<(- n x)(- y n))x y))))

```

Try it online!
> 1 votes

# Answer
# Perl 6, 38 bytes

```
{(0,1,*+*...*>$_).sort((*-$_).abs)[0]}

```

Test it

```
{   # bare block lambda with implicit parameter ｢$_｣

  ( # generate Fibonacci sequence

    0, 1,  # seed the sequence
    * + *  # WhateverCode lambda that generates the rest of the values
    ...    # keep generating until
    * > $_ # it generates one larger than the original input
           # (that larger value is included in the sequence)

  ).sort(           # sort it by
    ( * - $_ ).abs  # the absolute difference to the original input
  )[0]              # get the first value from the sorted list
}

```

For a potential speed-up add `.tail(2)` before `.sort(…)`.

In the case of a tie, it will always return the smaller of the two values, because `sort` is a stable sort. (two values which would sort the same keep their order)
> 1 votes

# Answer
# Pyth, 19 bytes

```
JU2VQ=+Js>2J)hoaNQJ

```

Try it here

### Explanation

```
JU2VQ=+Js>2J)hoaNQJ
JU2                  Set J = [0, 1].
   VQ=+Js>2J)        Add the next <input> Fibonacci numbers.
              oaNQJ  Sort them by distance to <input>.
             h       Take the first.

```
> 1 votes

# Answer
# Haskell, 48 bytes

```
(%)a b x|abs(b-x)>abs(a-x)=a|1>0=b%(a+b)$x
(1%2)

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 28 bytes

```
{F@&x=&/x|:-x-:F:x(+':1,)/1}

```

Try it online!

* `F:x(+':1,)/1` generate the first `x+1` terms of the fibonacci sequence, storing in `F` (adapted from @ngn's answer here)
* `x-:F` get the difference between `x` and each term of the sequence, updating `x` (which now becomes a list)
* `x|:-x` take the absolute value of each, updating `x`
* `&x=&/x` identify indices in sequence with the smallest value
* `F@` index into the actual sequence
> 1 votes

# Answer
# Perl 5 `-p`, 48 bytes

```
($a,$.)=($.,$a+$.)while$.<$_;$_=2*$_-$a<$.?$a:$.

```

Try it online!
> 1 votes

# Answer
## Pyth, 27 bytes

```
J[Z1)WgQeJ=aJ+eJ@J_2)hoaNQJ

```

**Test suite.**

Python 3 translation:
```
Q=eval(input())
def a(x):
    return abs(Q-x)
J=[0,1]
while Q>=J[-1]:
    J.append(J[-1]+J[-2])
print(sorted(J,key=a)[0])

```
> 0 votes

---
Tags: code-golf, number, fibonacci
---


title: Valid Through The Ages

text:
# Question
Title: Valid Through The Ages
Inspired by this question on SO, your task is to produce a program that is valid in (at least) two major versions of your chosen language that produce different output.

## Rules

* Any language that has more than one major version can be used.
    + For the purposes of this challenge, I would suggest a "major version" is where the first number in the version number changes.
        - PHP 4 and PHP 5 are different, PHP 5.3 and PHP 5.4 are not.
    + However, since I don't know the versioning scheme for all languages, if you can argue your case well enough, I'm sure the community will determine if you have been fair in determining "major version" yourself.
* The code must be compiled and run with the same flags and input each time
    + Except to change the version of the language if this is pertinent
* Errors don't count as output and answers that produce errors are disqualified (rather than error output is just ignored)
* The program should take no input other than that required to make it run.
* For each given version, the output should always be the same
* The intention is that the change should be a consequence of a change in the language spec rather than the VM spec or environmental metadata

## Scoring

* type scoring for length, so `+1` for each char/byte
* `-1` for each character *difference in the length* of the output.
    + e.g. Version 1 outputs `abcde` (5 characters), Version 2 outputs `123abc` (6 characters) = `-1`

## Other Rules

* Standard exceptions apply - no external programs,web requests etc.
* Your program should terminate (within 2 seconds)
* Lowest score wins.

## "Better" Scoring

*Keep your original answers, in the interest of fairness, I'll mark the winner based on the original rules.*

Since my original scoring is fundamentally broken, why not re-score / retry with the following scoring system:

* type scoring for length, so `+1` for each char/byte
* `+1` for each character *difference in length* of output
    + `abcde` and `123456` -\> `+1`
* `-1` for each *unique character difference* in the output (capped to length of shortest output)
    + `abcde` and `123456` -\> `-5`
    + `12345` and `123456` -\> `-1`
    + `12345` and `123455` -\> `0`
* Scores closest to zero win
* In the event of a second tie break, simple score wins.

# Answer
**Revised answer for "better" scoring system**

# C89 / C99, Score: 0

My program is 52 characters long and uses the same mechanism as in my original answer to achieve the different output. This works because C89 doesnt treat `//` as a comment:

```
i=32;main(){putchar(i+++0//**/
+52)&&i<84&&main();}

```

The results:

```
$ ./diff2c89
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS
$ ./diff2c99
TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂Çüéâäàåç
$ ./diff2c99 | wc
      0       1      52
$ ./diff2c89 | wc
      0       1      52
$ wc diff2.c
      1       2      52 diff2.c

```

**Old answer:**

# C89 / C99, Score: -Infinity?

I'm not entirely sure if this program doesn't break the rules, but never mind. This program exploits the fact that in C89 `//` is not a valid comment but `/* ... */` is.

Using the comment trick an other function is executed. In C89 the function just prints `"trolololol..."` until the stack overflows (so it might finish within 2 seconds).

```
f1(){printf("ol");f1();}
f2(){printf("oll");}
main(){
    printf("tr");
    void (*f[])() = {f1,f2};
    f[0 //* trollololol */
      +1]();
}

```

## C99

```
$ ./diffc99
troll

```

## C89

```
$ ./diffc89
trolololololololololololololololololololololololololololololololololololololololololo
lolololololololololololololololololololololololololololololololololololololololololol
ololololololololololololololololololololololololol ....

```
> 39 votes

# Answer
# Python - 10 points less than the next best answer

```
print(range(100))

```

In Python 2, this will print the entire list of integers from 0 to 99.

In Python 3, `range` is a generator and so it will print only "range(0,100)".

Seeing as I've never run into a size limit on numbers in Python, I can replace that 100 with a much bigger number (2\**1000, for example) and end up with a virtually infinite difference in the output.

*Edited to reflect the fact that, while I can get a score that is infinitely low for any practical purpose, I cannot reach actual infinity with a program that terminates under 2 seconds*

For the updated tie-breaker scoring system, I'd submit:

```
print(range(4))

```

Output:

Python 2: `[0, 1, 2, 3]`

Python 3: `range(0, 4)`

The first print has 5 unique characters (`[123]`), the second print has 8 unique characters (`range(4)`), the difference in length of output is 1, the code has 15 characters, the shortest output is 11 characters... these rules are pretty confusing but I think this brings me to a final score of 15+1-min(11,5+8) = 5.
> 16 votes

# Answer
# Python - 0 points

No idea how this one works :P Just stumbled upon it while trying out random code.

```
int

```

On Python 3, it's `<class 'int'>` and on Python 2, it's `<type 'int'>` (using interative console)
"Better" Score: 3 (length) + 1 (char diff.) - 4 (unique chars)

## Older Python 1 - 7 points

```
print()

```

Big thanks to @grc for this version and helping me subtract four points !

In Python 2, this statement is interpreted as `print ()` which prints the empty tuple `()`.
In Python 3, the `print` is a function and results in nothing being printed.
"Better" Score: 7 (length) + 2 (char diff.) - 2 (unique chars)

### Older Python 2 - 13 points:

```
print(1,2)

```

"Better" Score: 12 (length) + 2 (char diff. o/p) - 1 (unique chars o/p)

I know this isn't going to win but still gave an answer, as this is my first Python try :)
> 13 votes

# Answer
## C#

I also changed the generic method type inference algorithms between C# 2, 3 and 4. For example:

```
using System;
class C
{
  static int M<T>(T x, T y) { return 1; }
  static int M(object x, object y) { return 2; }
  static void Main()
  {
    Console.WriteLine(M(1, new int?()));
  }
}

```

In C# 2 method type inference says that T cannot be both `int` and `int?`, and so produces `2`. In C# 3 method type inference says "the best compromise between `int` and `int?` is `int?`" and so chooses `M<int?>` and produces 1.
> 13 votes

# Answer
# Ruby, 4 characters + 0 char length difference - 3 unique char difference = score of 1

```
p ?d

```

On Ruby 1.9, it will print `"d"`. On 1.8, it prints `100`.

Explanation: `?d` is `"d"` in 1.9 and `100` (the ASCII code for d) in 1.8. `p x` is equivalent to `puts x.inspect`. `*` is both string repetition and multiplication.

---

"Optimized" version for old scoring:

# Ruby, 8 characters - 999999989 chars difference = score of -999999981

```
p ?!*1e9

```

Prints `33000000000.0` for 1.8 and `"!!!!!!`...`!!!"` for 1.9. (`?!` is `33` in 1.8 and `"!"` in 1.9, and `*` is both string repetition and multiplication.)

Really, you could go as far as you wanted with the multiplication, it just depends on how fast your computer is.
> 9 votes

# Answer
## Bash — -∞ (up to practical limits)

Effectively, however much memory you have. E.g. with about 10GB:

```
echo {0..999999999}

```

Bash 2: doesn't support ranges in brace expansion, so prints `{0..999999999}`.

Bash 3:

---

## Any language — -∞ (up to practical limits)

You'll have this in pretty much any language, even if it ends up being a little more complex. As soon as you can make two different values, you can write code that produces arbitrarily different output. A better scoring method would ignore the differences in the output.

```
version = … # some arbitrarily weird stuff
if version = 2:
    while not timed_out():
        print "version2"

```
> 8 votes

# Answer
## C#

Following code would produce the different output for C# 5.0 and previous versions of C#

```
using System;
using System.Collections.Generic;

namespace TestConsoleAppClosure
{
    class Program
    {
        static void Main(string[] args)
        {
            var actions = new List<Action>();
            List<int> list = new List<int> { 10, 20, 30, 40 };
            foreach (var item in list)
            {
                  actions.Add(() => Console.WriteLine(item));
            }
            foreach (var act in actions) act();
        }
    }
}

```

**Output: C# 5.0**

```
10
20
30
40

```

**Output: C# 4.0**

```
40
40
40
40

```

The reason is explained in this blog post by Eric Lippert: Closing over the loop variable considered harmful.
> 4 votes

# Answer
## Python, -14 Points ( 3 - 17 char length difference = -14)

```
2/3

```

Python 2 outputs: `0`

Python 3 outputs: `0.6666666666666666`

## Better Scoring version, 5 points (3 + 2 char length difference = 5)

```
3/2

```

Python 2 outputs: `1`

Python 3 outputs: `1.5`
> 4 votes

# Answer
## C#

I added covariance and contravariance to C# 4, so programs of the form:

```
using System;
using System.Collections.Generic;
class C
{
  static void Main()
  {
    Console.WriteLine((new List<string>()) is IEnumerable<object>);
  }
}

```

Would produce `false` in C# 2 and 3 and `true` in C# 4.

However, one might argue that this does not count because the *library* containing the definition of `IEnumerable<T>` also had to change.
> 4 votes

# Answer
## **C++98/11 - "Better" Scoring (115 characters - 115 unique character differences in output = score of 0)**

**A slightly edited version to comply to the new scoring rules**

Golfed:

```
#include<cstdio>
#define u8 "\x0B"
int main(){int i=116;char c[i];c[--i]=0;while(i-->0)c[i]=u8"\x7E"[0]+i;puts(c);}

```

Ungolfed version:

```
#include <cstdio>
#define u8 "\x0B"
int main() {
    int i = 116;
    char c[i];
    c[--i] = 0;

    while(i-- > 0)
        c[i] = u8"\x7E"[0] + i;

    puts(c);
}

```

The new solution doesn't differ much to the old one. In the new solution the output in both C++11 and C++98 is with 116 characters equally long, but the only character they have in common is the new line character appended by the puts function.

For C++98 the `u8` in `u8"\x7E"[0]` will still be replaced, but now with `"\x0B"`. So the resulting value after preprocessing will be `"\x0B""\x7E"[0]`. The two strings will be concatenated to `"\x0B\x7E"` and the subscript operator will access the first element, in this case the character with the value 11 in the character encoding. Additionally the value of `i` will be added, which intially is 114. So the character with the value 125 will be written to the resulting array. As `i` goes to zero all values from 125 to 11 will be written to the array and `puts` will print all characters with the values from 11 to 125, plus the trailing new line.

In C++11 `u8"\x7E"[0]` will be interpreted as an UTF-8 string consisting of the single character with the hexadecimal value 7E. The subscript operator will now access this character and the value of `i` is added to it, resulting in the decimal value 241 during the first iteration. While `i` goes to zero, all the values down to 126 will be written to the array and `puts` will print the characters with the values from 126 to 241, plus the trailing new line.

Depending on the used character set, this will produce different results, as most character sets only have the first 128 characters in common.

For ISO-8859-2 the output would be the following:

C++98:

C++11:

**C++ (106 characters - 107 difference in output = score of -1) (OLD RULES)**

Golfed:

```
#include<cstdio>
#define u8 "f"
int main(){int i=108;char c[i];c[--i]=0;while(i-->0)c[i]=u8""[0];puts(c);}

```

Ungolfed version:

```
#include <cstdio>
#define u8 "f"

int main() {
    int i = 108;
    char c[i];
    c[--i] = 0;

    while(i-- > 0)
            c[i] = u8""[0];

    puts(c);
}

```

Compiled with `g++ -std=c++98 main.cpp` and `g++ -std=c++11 main.cpp`.

Actually you can replace `108` with any positive number in integer range to achieve negative scores. As long as it's bigger than 108 ;)

In C++98 `#define u8 "f"` will cause the preprocessor to replace `u8""[0]` with `"f"""[0]`. This will result in `"f"[0]`, which finally becomes the single character `'f'`, which is written to an array.

`puts(c)` will print the resulting array, consisting of i-1 `'f'`.

In C++11 `u8""[0]` will cause the empty string to be interpreted as an UTF-8 string, so no string concatenation is done. As this is a C-string, the subscript operator will access the terminating null-byte and write it to an array.

In the end `puts(c)` will print the resulting array, which consists only of null-bytes. But as `puts` stops reading the input as soon as it encounters a null-byte, it will only print a newline and nothing more.
> 3 votes

# Answer
**CSS2 vs CSS3 48 points**

```
<i style='font-feature-settings:"smcp" on;'>abcdefghijklmnopqrstuvwxyz</i>

```

Rendered as `ABCDEFGHIJKLMNOPQRSTUVWXYZ` (small caps) on CSS3 browsers

Rendered as `abcdefghijklmnopqrstuvwxyz` on non-CSS3 browsers

74 chars - 26 unique chars difference = 48
> 2 votes

# Answer
# Python - 0

```
a='a=%r\ntry:print a%%a\nexcept:pass'
try:print a%a
except:pass

```

Python 2 prints a quine, while Python 3 prints nothing.

EDIT: Updated, fixed.
> 2 votes

# Answer
**Perl, 24 characters - (9\*(10^9))-1 char difference = score of -((9\*(10^9))-1)+24**

```
print$]>=5?"a":"a"x9e9;

```

Prints 9e9-times `a` for all versions below 5, prints `a` for all versions above 5. You could make the score infinitely low by just adding more `a`s to the second output.
> 1 votes

# Answer
# Befunge, 36 - 378 = -342; 164 - 2576 = -2412

```
"v
"<v
" <v
"  <v
"   <v
 <v:,<
 ^_@

```

In Befunge 93, this would output 3 spaces, followed by `<v`, followed by 76 spaces, followed by `<v`, then 76 space, then `<v`, then 76 spaces, then `<v` followed by 77 spaces, then `v` followed by 78 spaces. Length: `3 + 2 + 76 + 2 + 76 + 2 + 76 + 2 + 77 + 1 + 78 = 395`This is trivially extendable by adding extra lines similar to the first 5 lines.

In Befunge 98, this would output  `<v <v <v <v v`.

The difference in length: `395 - 17 = 378`. So the score would have been (by the old rules): `-342`

<sub>Note: I could have gotten an even bigger difference if I used `.` instead of `,`; the difference would have been `-684`</sub>

---

Rule change:

This is a bit more tricky.

```
"  "-v>"Befunge 93 very long strings"v>"F"0g" "1-`!#v_   "F"0g1-"F"0pvz
     _^p0"F"-1g0"F"_v#    `-1" "g0"F"<^"j++a81zzzzzz]zzzzzzzzzzzzzzz"<
             _@#`0:,<

```

Befunge 93 output:

```
sgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeBsgnirts gnol yrev 39 egnufeB

```

Befunge 98 output:

```
j++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzzj++a81zzzzzz]zzzzzzzzzzzzzzz

```

Lengths: `2576`. None of the characters between the strings are the same, so if I understood the challenge correctly, my score is `164 - 2576 = -2412` (yes I was supposed to aim for `0`, but this was more fun). If I need to make it so that each character in each string are unique and different from each other, I can do so, please tell me.
> 1 votes

# Answer
## Powershell, "Better" scoring, -163 (15 - 178 char diff = -163 )

```
$PSVersionTable

```

**Powershell V2**

```
Name                           Value
----                           -----
CLRVersion                     2.0.50727.5477
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

```

**Powershell V3**

```
Name                           Value
----                           -----
WSManStackVersion              3.0
PSCompatibleVersions           {1.0, 2.0, 3.0}
SerializationVersion           1.1.0.1
BuildVersion                   6.2.9200.16398
PSVersion                      3.0
CLRVersion                     4.0.30319.1022
PSRemotingProtocolVersion      2.2

```
> 1 votes

# Answer
# JavaScript (ES3 vs ES5) - 9 points

length `10` **+** length difference `0` **-** output difference `1`

```
[].map?1:0

```

Outputs `1` for modern browsers that support Array.prototype.map. Outputs `0` on older browsers. I tested this with IE8.

# With old rules: 0 points

length `26` **-** length difference `26`

```
Array([].map?27:0).join(0)

```

Outputs `00000000000000000000000000` on modern browsers. And empty string on old.
> 1 votes

# Answer
# Java (around -2.000.000.000)

The Java versions are sometimes called 1.x, but I think it still is within the rules.

The easy way is to check whether a class exists that was introduced in a specific version.

```
try {
    Class.forName("java.lang.AutoCloseable");
    // Java 7 or later
    char[] text = new char[Integer.MAX_VALUE];
    Arrays.fill(text, 'a');
    System.out.println(new String(text));
} catch (Exception e) {
    // Java 6 or earlier
    System.out.println("-");
}

```

(Depends a bit on your terminal whether it is possible to output 2 billion characters in two seconds / For the new scoring, replace `Integer.MAX_VALUE` with the byte count of the program to achieve perfect zero score.)

This code depends on the version of the VM/JDK that is used (does that count?)

```
import java.lang.reflect.Field;
import java.util.Arrays;

{
    Field fValue = null;
    for (Field f: String.class.getDeclaredFields()) {
            if (f.getName().equals("value")) {
                    fValue = f;
            }
    }
    char[] text = new char[10];
    Arrays.fill(text, 'a');
    String s1 = new String(text);
    String s2 = s1.substring(1);
    fValue.setAccessible(true);
    text = (char[]) fValue.get(s2);
    Arrays.fill(text, 'z');
    System.out.println(s1);
}

```

It prints `z`s for Java 6 and earlier JDKs and `a`s for recent versions.
> 1 votes

# Answer
# PHP, Score: 0 (best case)

```
srand(2);echo rand();

```

Wow, this is going to be fun to explain.

According to this website, the `srand()` function appears to be broken from **PHP 5.1.5** to **PHP 5.3.14**. Therefore, we are going to keep under consideration PHP 4.4.9 and one random version of PHP 5 that falls in the version interval specified above.

**PHP 4.4.9 output:** `1505335290`

I don't think this is rule-breaking; Since this appears to be a bug, the output **should** be the same, but it's not. Our other PHP version will simply skip the `srand()` function and output a random number.
> 1 votes

# Answer
# C++98/C++11

```
#include <iostream>

int main()
{
  for (long i = 0; i < __cplusplus; ++i)
     std::cout << "x";
}

```

For a standard conforming C++98 compiler, this outputs 199711 times the letter 'x', while for a standard conforming C++11 compiler, this outputs 201103 times the letter 'x'. The length difference of the output is therefore 1392 characters. This means that actually golfing the source code is not worthwhile, since a much larger effect can be achieved by just replacing `"x"` with a longer string, or by multiplying `__cplusplus` with some number.
> 1 votes

# Answer
# TI-Basic 83 Plus vs. 84 Plus, score 5-1 = 4

```
length("setTime(

```

Outputs `2` on the TI-83 Plus, where the same program is parsed as something that looks like `length("?►DMS` because the `setTime(` command had not yet been introduced. So the string contains two 1-byte tokens, its length is 2.

Outputs `1` on the TI-84 Plus, because a string containing a single 2-byte token has length 1.
> 1 votes

# Answer
## APL (5 - (1988894 - 1) = -1988888)

In old-style APLs (like Dyalog if `⎕ML=0`\*),  means *mix*, which, on a 1-dimensional vector does nothing. In APL2-style APLs, like GNU APL, (or Dyalog if `⎕ML=3`),  means *first*, which takes the first item of a vector.

Thus, the following `5` bytes (the APL charset *does* fit in a byte),

```
↑⍳3e5

```

will output `1988894` bytes (the space separated list of numbers from 1 to 3e5) in old-style APL dialects,

and `1` byte (just the first number in said list, which is `1` and therefore of length `1`), in APL2-style APL dialects.

Notes:

* `⎕ML` means *migration level*. In Dyalog APL, the higher you set `⎕ML`, the more APL2-style features are enabled. It defaults to `0`. (And it's a global variable! Fun!)
* `3e5` was the highest 3-character value Dyalog APL would accept with . `4e5` gave me a `LIMIT ERROR`. This restriction is probably interpreter-dependent. (GNU APL had no trouble with higher values.)
> 0 votes

# Answer
# Bash 7 (14 bytes program length + 0 difference in output length - 7 difference in unique chars in output)

Related to @Gilles answer, but a different expansion feature and different versions. Scoring according to the edited question:

```
echo {1..9..2}

```

Output for bash 3.x:

```
{1..9..2}

```

Output for bash 4.x:

```
1 3 5 7 9

```
> 0 votes

# Answer
### C89/C99 comment exploit, 45 character, 0 score

```
main(a){while(++a<47)putchar(79-a//**/~0
);}

```

### c89 output

`QRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}` \- 45 char.

### c99 output

`MLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!` \- 45 char.
> 0 votes

# Answer
# PHP: −134217684 (43 - 134217727)

```
echo str_pad("",ip2long("")&0x7ffffff,"a");

```

Usage:

```
time php -r 'echo str_pad("",ip2long("")&0x7ffffff,"a");' > /tmp/test
1.61user 0.17system 0:01.79elapsed 99%CPU (0avgtext+0avgdata 142272maxresident)k
0inputs+0outputs (0major+35922minor)pagefaults 0swaps

```

In PHP5+ this will print nothing since ip2long with invalid argument turns into false which casts to zero. In PHP4 it `ip2long("")` returns -1 and we pad the empty string with 128MB og `a`.

The mask is fitted so that it returns long before the 2 seconds on my machine. If you can't make it in 2s buy better hardware!

# With new rules: 0 (40 - 40. You can't get any closer to zero.)

```
echo str_pad("",40,chr(97+ip2long("")));

```

Outputs:

```
In PHP4: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
In PHP5: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

```
> 0 votes

# Answer
# SmileBASIC 3 / SmileBASIC 2, Score: -5 (original scoring)

```
?1E9

```

In modern versions of SB, this prints `1000000000` as expected, but in version 2 and earlier it printed `10` due to a bug.
> 0 votes

# Answer
# Go 1.9-\>1.10. Score = 1 - 1 = 0

From 1.10 notes:

> There is no longer a limit on the GOMAXPROCS setting. (In Go 1.9 the limit was 1024.)

```
package main
import (r"runtime")
var g=r.GOMAXPROCS
func main() {g(10340)
print(g(0))}

```

1.8: `256`

1.9: `1024`

1.10: `10340`
> 0 votes

# Answer
# ARMv4T/ARMv5TE+ with libc, `pop {pc}` bug, for old scoring system, ~~42~~ 40 bytes, old score ~~-4294967252~~ -4294967255

```
1009 e28f 4002 e92d e001 e04f f004 e49d
e002 e201 ff11 e12f 4674 2021 f7ff fffe
3401 d1fa bc01 4700

```

ARMv4T, the ISA used in the ARM7TDMI, famous for powering the Game Boy Advance, introduced the Thumb instruction set.

It is a 16-bit (later mixed with 32-bit) instruction set encoding that is more compact, but more limited, than the standard 32-bit ARM instruction set. I write a lot of my golfs in it, because it is ~~torture~~ fun.

Basically, the idea is, since ARM instructions are always 4 byte aligned, if you jump to an odd address, the CPU will switch to Thumb execution mode at the address rounded down, and vice versa for an even address.

One cool thing that ARM lets you do is `pop` the return address directly into the program counter from the stack, resulting in incredibly easy stack cleanup (similar to `leave; ret` in x86, but you can pop ALL registers at once)

```
        push    {..., lr} @ put the return address in the link register on the stack
        pop     {..., pc} @ pop the return address into the program counter to return

```

On ARMv5TE and later, this will magically switch between ARM and Thumb state.

However, ARMv4T had an infamous bug here.

They forgot to implement Thumb switching: `pop {pc}` will ignore the lowest two bits and not switch to Thumb mode. Source: ARM docs

So all we have to do is write a polyglot that will do something different if it is in ARM or Thumb state, which is easy because the encodings are entirely different.

```
        .text
        .arm
        .globl main
main:
        add     r1, pc, #9
        push    {r1, lr}
        sub     lr, pc, r1
@ define to simulate ARMv4T behavior
#ifdef SIMULATE_ARMV4T
        b       simulate_armv4t_bug
#else
        pop     {pc}
#endif
.Larmv4t_polyglot:
        and     lr, r1, #2      @ b     .Lthumb_entry; (skipped)
        bx      r1

        .thumb
.Lthumb_entry:
        mov     r4, lr
.Lloop:
        movs    r0, #'!'
        bl      putchar
        adds    r4, #1
        bne     .Lloop
        pop     {r0}
        bx      r0

#ifdef SIMULATE_ARMV4T
        .arm
        .align 2
simulate_armv4t_bug:
        pop     {r12}
        @ clear thumb bit
        bic     r12, r12, #3
        bx      r12
#endif

```

This program starts in ARM state.

We need `r1` to contain the address of `.Larmv4t_polyglot`, with the Thumb bit set. (So `.Larmv4t_polyglot | 1`, or `.Larmv4t_polyglot + 1`)

Therefore, we add 9 to the program counter (which points 8 bytes after the currently executing instruction because of questionable design decisions) to get 16 bytes, or 4 instructions, ahead, with the Thumb bit set.

```
        add     r1, pc, #9

```

Push `r1` and `lr` to the stack. The former is so we can perform the `pop {pc}` bug, and the latter is to save the return address so we can use `lr` as a temp register and make function calls.

```
        push    {r1, lr}

```

Subtract `r1` from `pc`. This results in `lr` being `-1`.

```
        sub     lr, pc, r1

```

Then, we pop the value from `r1` into the program counter.

An ARMv5+ processor will execute the polyglot in Thumb mode, but an ARMv4T processor will ignore the low 2 bits (rounding down) and execute `.Larmv4t_polyglot` as ARM code.

To simulate the buggy behavior, define `SIMULATE_ARMV4T` which will replace `pop {pc}` with a veneer that jumps to that address in ARM mode.

```
        pop     {pc}

```

Now, it is time for our polyglot.

**ARM mode:** Set `lr` to `0` by setting it to `r1 & 2`. Since that contains the address of `.Larmv4t_polyglot` plus one, we know the second bit is clear.

Then, jump to the polyglot again on ARMv4T (the address is still in `r1`), this time using `bx`, which DOES switch to Thumb mode.

```
.Larmv4t_polyglot:
        and     lr, r1, #2
        bx      r1

```

**Thumb mode:** Jump to `.Lthumb_entry`.

```
.Larmv4t_polyglot.thumb:
        b       .Lthumb_entry
        @ skipped

```

Now, we are in Thumb mode on both machines, we can do our output loop.

We first need to make a copy, because `lr` will be overwritten.

```
      mov     r4, lr

```

Then, we loop calling `putchar('!')`, until `r4 += 1` == 0.

```
.Lloop:
        movs    r0, #'!'
        bl      putchar
        adds    r4, #1
        bne     .Lloop

```

On ARMv5TE+, `r4` will be `-1`, so the loop will only run for one iteration, but on ARMv4T, `r4` will be `0`, so it will run `4294967296` times (`0x100000000`) until it wraps back around to zero.

I could technically make this infinite, but the rules say that it must eventually finish.

Equivalent C:

```
uint32_t r4 = lr;
do {
    putchar('!');
} while (++r4);

```

Finally, do an ARMv4T compatible return using the "Thumb interworking" hack: We pop into a low register and `bx` to it to return from `main`.

```
        pop     {r0}
        bx      r0

```

Program size: 40 bytes

Output length in ARMv5TE+: 1 byte

Output length in ARMv4T: 4294967296 bytes

**Score: -4294967255**

# ARMv4/ARMv5TE+ with libc, same bug, for new scoring system, 42 bytes, score 0

Mostly the same, but instead of dumping near-infinite `'!'`s, both will dump 42 bytes to `stdout`. However, for a maximum negative score, all you have to do is change `movs r5, #42` to `movs r5, #128` for a score of -86.

Machine code:

```
1009 e28f 4002 e92d e080 e3b0 f004 e49d
e002 e201 ff11 e12f 252a 4676 19a8 f7ff
fffe 3d01 d1fa bc01 4700

```

(ARMv4T simulator left out, it is the same)

Assembly:

```
        .text
        .arm
        .globl main
main:
        add     r1, pc, #9
        push    {r1, lr}
        movs    lr, #128
        pop     {pc}

.Larmv4t_polyglot:
        and     lr, r1, #2      @ b     .Lthumb_entry; (skipped)
        bx      r1

        .thumb
.Lthumb_entry:
        movs    r5, #42
        mov     r6, lr
.Lloop:
        adds    r0, r5, r6
        bl      putchar
        subs    r5, #1
        bne     .Lloop
        pop     {r0}
        bx      r0

```

The main differences are that instead of initially setting `lr` to `-1`, we set `lr` to `128`, and that our print loop will always run 42 times, subtracting 1 from the char it prints each time.

The equivalent C loop looks like this:

```
uint32_t r5 = 42, r6 = ARMv4T ? 0 : 128;
do {
    putchar(r5 + r6);
} while (--r5);

```

ARMv5TE+ output

```
termux ~/golf $ clang -m32 valid-through-the-ages.S
termux ~/golf $ ./a.out | hexdump -C | cut -d' ' -f 3-19
aa a9 a8 a7 a6 a5 a4 a3  a2 a1 a0 9f 9e 9d 9c 9b
9a 99 98 97 96 95 94 93  92 91 90 8f 8e 8d 8c 8b
8a 89 88 87 86 85 84 83  82 81

```

ARMv4T (simulated) output:

As stated before, the compiler option is just to emulate the bug on my device. It is not needed on actual hardware.

```
termux ~/golf $ clang -m32 valid-through-the-ages.S -DSIMULATE_ARMV4T
termux ~/golf $ ./a.out | hexdump -C | cut -d' ' -f 3-19
2a 29 28 27 26 25 24 23  22 21 20 1f 1e 1d 1c 1b
1a 19 18 17 16 15 14 13  12 11 10 0f 0e 0d 0c 0b
0a 09 08 07 06 05 04 03  02 01

```

Program size: 42 bytes

Difference in output length: None

Differing bytes: 42.

**Score: 0**
> 0 votes

---
Tags: code-challenge, polyglot
---