[Question]
  [
# Task
Write a program/function that when given a positive integer \$n\$ and a digit \$d\$ which is not 0 outputs a way to represent \$n\$ using only addition, subtraction, multiplication, exponentiation, division, concatenation, parenthesis and the digit \$d\$.
# Examples
```
n =  6, d = 1  =>  (1 + 1) * (1 + 1 + 1)
n =  6, d = 1  =>  1 + 1 + 1 + 1 + 1 + 1
n = 10, d = 1  =>  1 || 1 - 1
n = 12, d = 1  =>  1 || (1 + 1)
n = 64, d = 2  =>  2 ^ (2 + 2 + 2)
n =  1, d = 9  =>  9 / 9
```
**Note:** In the examples `||` represents concatenation
# Output Format
* Concatenation must be explicit with a separate operator
* Output can be a string, list of operations and numbers or a list of lists in place of brackets.
* You may choose the precedence of the operators but it must be consistent for all outputs produced by your program/function
* Output may be in [polish](https://en.wikipedia.org/wiki/Polish_notation), [reverse polish](https://en.wikipedia.org/wiki/Reverse_Polish_notation) or [infix](https://en.wikipedia.org/wiki/Infix_notation) notation but it must be consistent for all outputs produced by your program/function.
* You can use custom symbols for representing the digits and operations but the symbols used for representing the digits and operations should be distinct.
# Scoring
This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), Your score will be
```
100*B + S
```
Where `B` is the number of bytes in the program/function, and `S` is the sum of the number of times the digit \$d\$ appears in the representation of \$n\$ with the digit \$d\$ as returned by your program/function for all \$n \le 1000\$ and all \$d\$ from 1 to 9
Lowest score wins
Example: if your program is `abcd` and all representation of \$n\$ returned by your program has 5 occurrences of \$d\$ then its score will be `(4 * 100) + (5 * 1000 * 9) = 45400`
# Rules
* Your program/function should run deterministically, so that it always returns the same representation for a given \$n\$ and \$d\$ (and hence always gets the same score).
* Your answer must include not only your submission, but also the code you used to calculate the `S` part of its score. This need not be written in the same language as your submission, and will not be counted towards its byte count. You are encouraged to make it readable.
* Your answer must include the precedence of the operators needed to evaluate the outputs produced by your program/function
* You must actually run your test program and calculate/verify your score before submitting your entry. If your submission runs too slowly for you to verify its score then it is not qualified to compete, even if you know what its score would be in principle.
---
*Inspired by [this video](https://youtu.be/-ruC5A9EzzE)*
  
[Answer]
# [Python 3](https://docs.python.org/3/), 210 bytes · 100 + 59045 digits = 80045
```
def f(n,d):
 m={d:d},
 while{n}-{*m[0]}:m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m
 return m[0][n]
```
[Try it online!](https://tio.run/##NY7RasMwDEXf8xUiMLBdhTRsMGa6/ohxYeCYGmbHCRmz4vrb0yRjDxfO1ZFAkeb7EF7X1fQWLAtouKzAf2YjTcEKfu/uu8@hNFl4ddZFbmqRLKqkccBRkeZ2mCDiCC7A4iLz6JWUTfcn0j6OsCPtOB644PC/rtKJMDVbBCFdPr6CgSQ2Ti906Y7WtoQuzMzWOZVMpeYa61Mjbu2j5s7Ccj0XFL6CqZ9/pgD7oyroNU7HFXvrOnznfH0C "Python 3 – Try It Online")
### Scoring
Scoring goes much faster using this modified version that solves 1 through 1000 all at once:
```
def f_gen(d):
 m={d:d},
 while 1:yield from m[0].items();m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m
def size(expr):
    return 1 if isinstance(expr, int) else size(expr[0]) + size(expr[2])
score = 0
for d in range(1, 10):
    s = set(range(1, 1001))
    for n, expr in f_gen(d):
        if n in s:
            s -= {n}
            score += size(expr)
            print(n, expr)
            if not s:
                break
print(score)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), Score: ~~87900 ... 83274~~ 82574
## 229 bytes x 100 + 59674 digits
Takes input as `(d)(n)`. Returns a string. Uses `|` for concatenation.
```
d=>n=>[0,v=[d],F={[d]:d},s={[d]:0}].map(_=>v.map(x=>v.map(y=>[x+y,x-y,x*y,x/y,x**y,[x]+y].map((z,o)=>z<0|z>1e4||z%1?0:(!F[z]&&V.push(+z))|(S=s[x]-~s[y])<s[z]?F[s[z]=S,z]=`(${F[x]+'+-*/^|'[o]+F[y]})`:0)),V=[])&&v.push(...V))&&F[n]
```
[Try it online!](https://tio.run/##ZUzLboMwELz3Lyo1xBuMA1GSBhSTm38gEhfLbVAgfSjFqG4RONBfp0tRTxxmZ3Y0M@9plZrz51v55RU6y/sL7zMeFzyWPq24zBQV/IYUZR01o/I7xT7SkjzzuPoT9b9osFa7Da09xAKxHBiFrJXbjC1iqQYe273f2jjI121rZ8HBj8i9kFY5TsLKb/NKXAvQkiM3WPV@jGwU7A0GDkIOxI8Uz4k83MSwPXe9xfKpnUutXIHZDk6RD0ATLhU4TjVuMsYSwFfIQvVnXRh9zdlVv5ALCYBsHrcAdxN7F24m9grIdj1xQyDhDjf6Xw "JavaScript (Node.js) – Try It Online")
### Scoring
Because the golfed version is quite slow, the total score was computed with the following ungolfed version which, given \$d\$, computes the formulas for all \$n\in[1..1000]\$ at once.
Although it works on TIO, the output is too long. So the link below is an example for \$d=9\$.
[Try it online!](https://tio.run/##fVRNc5swEL37V2wPCRA@AolzaDDpqedkpjO9MOoMBTmhpVIGBMGO@e3uSkI2OBlzkNa7b9/bXUv6k3VZk9flq/AZL@h@n3PWCHh8ggRSy7U8sHy5XMnlWi6/5LLbWSReLNYty0XJGTS86qhdOPC@AKiogC6rWio5oADioVN@a17/a6sM3e@QFgTuMTiYYFNu6SQSHiOCi6zCUIiKisSWCqXy4LaCJW6uq8W1PKNvP00FRKWBLinA9O9Z/mL3kDyMCaehzTQEkIYeRB7ceHDrwdKDO3JA8jlybH3UG9t6K4VEOjMcQJ41FMJ76LDEHlzYxPC7ptnf@CMqMqgVbOAbsLaqcEA9@OeSbkzS1TnUrUFdzKmvzyUtD9Rnue80zLX7QPAfoi7Zs@3ITic/nU/Sh@n4yrXdwZck0aVdXiLlKoEoxO90onL2zRYV5UlKe4JSytpIK5r9KYrXHo9j2hFIUKFlBV2XjBZSxhyg4LVtXuzOcWC3k@wrzdmRU/XD6VZ0YNkWqhqXKubxKeVk4lR1WY4Vn/CMArKR7Tw2LD6zB8egjGX27thBEASmJRUcpleJoVYU4zaOFs3jdZIPAq9oUPFnm3m6OqZG6h1aYWRU1FfVTaYwLTcnsnz/Ad8RBVepNRVtzbQjXgx7/aB8dfb/AQ "JavaScript (Node.js) – Try It Online")
```
const OP = ['+', '-', '*', '/', '^', '||'];
function solve(d) {
  let value = [ d ],
      formula = { [d] : d },
      size = { [d] : 0 },
      total = 0;
  for(let i = 0; i < 4; i++) {
    let newValue = [];
    value.forEach(x => {
      value.forEach(y => {
        [0, 1, 2, 3, 4, 5].forEach(o => {
          let v;
          switch(o) {
            case 0: v = x + y; break;
            case 1: v = x < y ? null : x - y; break;
            case 2: v = x * y; break;
            case 3: v = x % y ? null : x / y; break;
            case 4: v = x ** y; break;
            case 5: v = +(x.toString() + y.toString()); break;
          }
          if(v !== null && v <= 10000) {
            let sz = size[x] + size[y] + 1;
            if((formula[v] === undefined && newValue.push(v)) || sz < size[v]) {
              formula[v] = '(' + formula[x] + OP[o] + formula[y] + ')';
              size[v] = sz;
            }
          }
        });
      });
    });
    value.push(...newValue);
  }
  for(let n = 1; n <= 1000; n++) {
    console.log(n, size[n] + 1, formula[n]);
    total += size[n] + 1;
  }
  console.log('-->', total);
  return total;
}
let score = 0;
for(let d = 1; d <= 9; d++) {
  score += solve(d);
}
console.log('Final score:', score);
```
[Answer]
# [Wren](https://github.com/munificent/wren), 107 bytes, score: 138373
Thanks to @Mukundan for the golfing so far!
(This answer was written before @GammaFunction did so.)
```
Fn.new{|n,d|"%(n)".map{|i|Num.fromString(i)}.map{|i|i<1?[d,-d]:[d]*(i/d).floor+["%(d)/%(d)"]*(i%d)}.join()}
```
[Try it online!](https://tio.run/##VVBdT4MwFH3vr7iSLGk3LCxGjYvEaET34KbZ8InsgdAya6BduuJigN@OBTaNL7ftPR@95x40l@1XoiErZQoBtE@SSn6oaumy2hlhSRxaJLuqFvWyLGimVbE2WsgtFqQ5IeJ2ehcz95xtZjHbjLHwGKFZrpSexNaDEa8rToeMmJV9KiExadr1997wgu6sn8HdADRN8hxf@ZfuBSEI/cOdIAhgnSrNwd4cC3serMJFuHgIVxC9wvvb430UQjQP4SVcPkfzM4S6ZPtBA1P/Gsa2@mCF9jGDnMut@QCVwV6VOuUIZUoDliAkTCm1VJ9AhQD6Nju2b4YeQGeuSrMrjXX/G1@6wEhPOP08nJMjmaaqlKbfm00CjBo1rLSxogY1v7kPWhiOezFpfwA "Wren – Try It Online")
[Answer]
# Brainfuck, 30 bytes \* 100 + 9009000 = 9012000
Uses the fact that `n = (d/d)*n`:
```
,>,>+<<->.>.<.<[->>>.<<.>.<.<]
```
In that program, the character representing division is ASCII 1 and the character representing addition is ASCII 0, so the output isn't very readable.
With [this TIO link](https://tio.run/##SypKzMxLK03O/m@nDQbRulCGtjaMYWMTa6cLFLaxsfmvY6cDYuja6dnp2ejZAFXbARk2EF7s//9clgA) I include a brief header making the output readable. There is still the minor inconvenience that input are ASCII characters (the link has a new line, ASCII 10, in the input, hence the program prints
```
9/9+9/9+9/9+9/9+9/9+9/9+9/9+9/9+9/9+9/9
```
To make 10. If instead you use [this interpreter](https://copy.sh/brainfuck/?c=PisrKysrK1stPisrKysrKysrPisrKysrKys8PF0-LS0-Kzw8PApTZXQgdXAgY2VsbHMgMyBhbmQgNCBmb3IgcHJldHRpZXIgcHJpbnRpbmcKTWVtb3J5IGlzCm4gfCBkIHwgMSAoZGl2aXNpb24gY2hhcikgfCAwIChhZGRpdGlvbiBjaGFyKQosPiw-Kzw8LT4uPi48LjxbLT4-Pi48PC4-LjwuPF0$), you can type easier to understand input, using `\` to insert the values of the ascii characters, instead of using the ascii characters. So, using `\10\57` as input in this program gives the same result as the program on TIO.
[Answer]
# [Zsh](https://www.zsh.org/), ~~89 81~~ 75 bytes, score: 135173
(total digit count is 127673)
```
for c (${(s::)1})(repeat c/$2 s+=($2);repeat c%$2 s+=($2/$2);<<<${s=$2-$2})
```
[Try it online!](https://tio.run/##PY7BTsMwEETv/opRu1VslTZOyqEN8Qdw4sINEanETtNDnSp2JITlbw8xAi4rzZuV5n25fu64CHM3jGjBKXBXVaKIgo/mbs4ebU4l3FZxKsXTH9v8szzhuq4pOEXljsoo5shYh8ejPODAmJ1uTvFQ7PeFlDIKpq@XX3BaElvD9wbeOI@L8Q7nj2HyOMoN9GANBovX55eHFDKPcbK4emY@l8OSstXJWVU7atJQhoyaNBAFfmqkXlktEBjj3E03bBUorCmsiHcgC9JiledvDen3GMVitOibth9Ay/f8DQ "Zsh – Try It Online")
(This generates the same operations that @a'\_''s method does. I thought of it independently, then saw his score using it, then implemented it.)
> 
> You can use custom symbols for representing the digits and operations [...]
> 
> 
> 
We take advantage of that here; concatenation is represented by a newline and addition is represented by space. Concatenation has lower precedence than addition, which has lower precedence than division.
```
for c (${(s::)1})(          # for each digit c in n
                            # repeat $x expands $x in arithmetic mode
    repeat c/$2 s+=($2)     # append d to $s, c/d times
    repeat c%$2 s+=($2/$2)  # append d/d to $s, c%d times 
    <<<${s=$2-$2}           # if $s is still unset, set it to d-d
                            # <<< prints $s, implicitly joined on spaces
)                           # exit the subshell, effectively unsetting $s
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 150 bytes × 100 + 81773 digits = 96773
```
⪫Ｅθ§⪪§⪪”}∧⟦NＪgＹＺＧ；|⪫v4⌈-LiςΠg➙∨Ｃ⊕⊙Nψ≧Fδ∨↧↧«3Ｙ!‴2ⅈ⸿⟦⁰J◨(⁴⦄4b¶¤⦄→₂⊞GςＧ⸿≡←ε⭆R？ρq＆Σ<×HJ⁶�⧴Q<"k~3Ｖu⌊+ＬΠ↓1βπt“P³∨Ｒ▶Ａ↓ⅉs▷"«‖κ-σ_←U/Ｖ!Ｕ⊕⁷↙Ｕ3M⁼³ＲＶＶ¤HＱ:”;Ｉη,Ｉι&
```
[Try it online!](https://tio.run/##jZHLCsIwFET3fkXJBUmaG@L7QVbiSkEQ/IKiQgulvor497EmaRtrUckiM8Odk6Tdx9F1f4pSrbfXJMvp@pRkdBOd6QWDRb7KDscH3Z3TJKfvjoAABAlIgQNzu6@sBtHmam3ViwPKELEI0QyhK5Y7d2eFjlG4LjABdvmu1qq8paFIjy7LU8ystD0Ii1UndVs0GKLJqjovhmp@m/e@S3krqaXbTgFe5dybscRPSgjS6H945Sz/5Ph/uXrxL@IXSvNeX99MMCCKMAyW0S2nMSsUwconzARdwpjSej6bTsaj4aDf64y1uKdP "Charcoal – Try It Online") Link is to verbose version of code. Uses `&` (low precedence) as concatenation and `#` to represent the input digit. Explanation: Simply looks up all of the digit patterns in a (compressed) hand-crafted lookup table and concatenates the relevant digits together. [Proof of digit count.](https://tio.run/##jZLdisMgEIVfJThQNCqm114tvepCYdk@gWRDVwimtGnZt7f@Jbpp6C5C5szkzKcm036rSzuo3tqPizYj3qmreww3J4@jq5wO6oyP516PGAEHBgIYBgokxVJFDXwtyzoqzwEZiMwVWTCx1DhFmvaqE8NlGyAc4iqzrOV0ykARBV1MuwSviH1Qu5UruZsvGHzJmns8Qy6/ze/@VKWrpJXedQrQuU4LTyQ@U2oQQf@HN3npM6f8y/ON/yK@oCzP9fLOiFVIIsKqPIx70/a3q753n8qcOrxl1bZpGmd5H7TB3hFmuHeVt3FvvrqfNL/asZhnhfeGECfRBsUIPkprLb/3Dw "Charcoal – Try It Online")
[Answer]
# [W](https://github.com/A-ee/w) `n`, 22 [bytes](https://github.com/A-ee/w/wiki/Code-Page) \* 100 + 127673 = 129 873
A blatant rip-off of my Wren answer.
```
☺◘Y╔û çτ◘↑═uon↕I6≡ÿÑ°t
```
Uncompressed:
```
1,             % Split number to chunks of 1
  c}           % Construct the list [input]
    ac/*       %   Repeat that input/current times
  c:{          % The list [input,input]
     '/,       % The string input/input
        }      % The list [input/input]
         acm*  %   Repeat that list input%current times
             + % Join these two lists
      |        % If that's the empty list:
  c:_{         %   Yield the list [input,-input]
       M       % Do that for every thing in the input
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), Score: 127,473 (178 bytes \* 100 + 109,673)
```
->n,d{n.to_s.chars.map{|c|g=d.to_s;c<?1?g+?-+g:(i=c.to_i)==d ?d:(d*d==i)?g+?*+g:i%d<1?([d.to_s]*(i/d))*?+:i>d ?g+?++f[i-d,d]:(i+1==d&&i>1)?g+?-+f[d-i,d]:[d==1?d:g+?/+g]*i*?+}*?|}
```
[Try it online!](https://tio.run/##XZHbrpswEEXf@YpRoh4ZTAim1bmkcfiIPnJQRW1ILKV2xOWhAr49HQOhTi0htGft2R7bdffrz70CDvfdSYey11FrfjaRuBR1E/0ubv0ghjOXU/W7OKYsPdN0R88HoriwVeVzLiGVByIDybnyrSFAg/oijywl2dybB0Ttpe8HKT2oEzagi9IqUzsZyhzTKMOclxd1Yv68RZXJnbIsw1iGG2B1T895oDBjDNJhvN@6toENeQ2B@cBPsO2rzIp83HgL@xpCsjIrHMZit3FSLmVPlP1HkyeaPNPXb@62k3Jokrh0Um5yCB//glE47OMNo95XOkvLvenB8BnZ27tnunbyc8hyj0XdrTUEI6WBQQ4e4FqKLI7jua7nul1Ld3TrmgupIlFcr0SHgG@3WlQFdaElSab@I7CV2LXMuu31GOKYclzmfQRfi6bFkR/2Ukvv8befEaKrSy1Ke4D4cZioLMQFehjMAI6DcjBRIwpN9p9y70fCdLqFcbmvH8LU5XJ58wUFgGcG6kQs1m0/GcbVgfOunnFz/ws "Ruby – Try It Online")
This uses `|` as concatenation. It could also definitely be cleverer. I just kept adding cases to try to minimse the occurences of `d`.
]