Count the number of shortest paths to nAndroid Lock ScreenFissile NumbersCo-primality and the number...

Did anybody find out it was Anakin who blew up the command center?

How can I draw lines between cells from two different tabulars to indicate correlation?

Is the internet in Madagascar faster than in UK?

Count the number of shortest paths to n

Who was the most successful German spy against Great Britain in WWII, from the contemporary German perspective?

Dealing with stress in coding interviews

What's the point of fighting monsters in Zelda BoTW?

Reusing studs to hang shoe bins

If I said I had $100 when asked, but I actually had $200, would I be lying by omission?

Is a memoized pure function itself considered pure?

Why is getting a PhD considered "financially irresponsible" by some people?

Biological refrigeration?

Weighted smooth histogram

Redacting URLs as an email-phishing preventative?

Why is strlen so complex in C?

Stuck on a puzzle

Is it unusual for a math department not to have a mail/web server?

Talk interpreter

Why is sh (not bash) complaining about functions defined in my .bashrc?

Does a Mace of Disruption's Frightened effect override some undead's immunity to the Frightened condition?

Is it ok to record the 'environment' around my workplace?

How many petaflops does it take to land on the moon? What does Artemis need with an Aitken?

How does the OS tell whether an "Address is already in use"?

Do sharpies or markers damage soft gear?



Count the number of shortest paths to n


Android Lock ScreenFissile NumbersCo-primality and the number piCompute minimax of an arrayDistance to four2D Array Middle PointDrawing convex polyiamondsRemoving points from a triangular array without losing triangles






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







17












$begingroup$


This code challenge will have you compute the number of ways to reach $n$ starting from $2$ using maps of the form $x mapsto x + x^j$ (with $j$ a non-negative integer), and doing so in the minimum number of steps.



(Note, this is related to OEIS sequence A307092.)



Example



So for example, $f(13) = 2$ because three maps are required, and there are two distinct sequences of three maps that will send $2$ to $13$:



$$begin{array}{c} x mapsto x + x^0 \ x mapsto x + x^2 \ x mapsto x + x^0end{array} qquad textrm{or} qquad begin{array}{c}x mapsto x + x^2 \ x mapsto x + x^1 \ x mapsto x + x^0end{array}$$



Resulting in $2 to 3 to 12 to 13$ or $2 to 6 to 12 to 13$.



Example values



f(2)   = 1 (via [])
f(3) = 1 (via [0])
f(4) = 1 (via [1])
f(5) = 1 (via [1,0])
f(12) = 2 (via [0,2] or [2,1])
f(13) = 2 (via [0,2,0] or [2,1,0], shown above)
f(19) = 1 (via [4,0])
f(20) = 2 (via [1,2] or [3,1])
f(226) = 3 (via [2,0,2,1,0,1], [3,2,0,0,0,1], or [2,3,0,0,0,0])
f(372) = 4 (via [3,0,1,0,1,1,0,1,1], [1,1,0,2,0,0,0,1,1], [0,2,0,2,0,0,0,0,1], or [2,1,0,2,0,0,0,0,1])


Challenge



The challenge is to produce a program which takes an integer $n ge 2$ as an input, and outputs the number of distinct paths from $2$ to $n$ via a minimal number of maps of the form $x mapsto x + x^j$.



This is code-golf, so fewest bytes wins.










share|improve this question











$endgroup$










  • 1




    $begingroup$
    I think it should be explicitly noted that the ^ symbol denotes exponentiation. It could be XOR as well (for instance C uses ^ for bitwise XOR).
    $endgroup$
    – Ramillies
    17 hours ago






  • 1




    $begingroup$
    @Ramillies Maybe it should be changed to MathJax. I.e. $x=x+x^j$ instead of x -> x + x^j.
    $endgroup$
    – Kevin Cruijssen
    17 hours ago










  • $begingroup$
    @KevinCruijssen: Good point, that would certainly help.
    $endgroup$
    – Ramillies
    17 hours ago










  • $begingroup$
    I have added this to the OEIS as A309997. (It will be a draft until approved.)
    $endgroup$
    – Peter Kagey
    11 hours ago


















17












$begingroup$


This code challenge will have you compute the number of ways to reach $n$ starting from $2$ using maps of the form $x mapsto x + x^j$ (with $j$ a non-negative integer), and doing so in the minimum number of steps.



(Note, this is related to OEIS sequence A307092.)



Example



So for example, $f(13) = 2$ because three maps are required, and there are two distinct sequences of three maps that will send $2$ to $13$:



$$begin{array}{c} x mapsto x + x^0 \ x mapsto x + x^2 \ x mapsto x + x^0end{array} qquad textrm{or} qquad begin{array}{c}x mapsto x + x^2 \ x mapsto x + x^1 \ x mapsto x + x^0end{array}$$



Resulting in $2 to 3 to 12 to 13$ or $2 to 6 to 12 to 13$.



Example values



f(2)   = 1 (via [])
f(3) = 1 (via [0])
f(4) = 1 (via [1])
f(5) = 1 (via [1,0])
f(12) = 2 (via [0,2] or [2,1])
f(13) = 2 (via [0,2,0] or [2,1,0], shown above)
f(19) = 1 (via [4,0])
f(20) = 2 (via [1,2] or [3,1])
f(226) = 3 (via [2,0,2,1,0,1], [3,2,0,0,0,1], or [2,3,0,0,0,0])
f(372) = 4 (via [3,0,1,0,1,1,0,1,1], [1,1,0,2,0,0,0,1,1], [0,2,0,2,0,0,0,0,1], or [2,1,0,2,0,0,0,0,1])


Challenge



The challenge is to produce a program which takes an integer $n ge 2$ as an input, and outputs the number of distinct paths from $2$ to $n$ via a minimal number of maps of the form $x mapsto x + x^j$.



This is code-golf, so fewest bytes wins.










share|improve this question











$endgroup$










  • 1




    $begingroup$
    I think it should be explicitly noted that the ^ symbol denotes exponentiation. It could be XOR as well (for instance C uses ^ for bitwise XOR).
    $endgroup$
    – Ramillies
    17 hours ago






  • 1




    $begingroup$
    @Ramillies Maybe it should be changed to MathJax. I.e. $x=x+x^j$ instead of x -> x + x^j.
    $endgroup$
    – Kevin Cruijssen
    17 hours ago










  • $begingroup$
    @KevinCruijssen: Good point, that would certainly help.
    $endgroup$
    – Ramillies
    17 hours ago










  • $begingroup$
    I have added this to the OEIS as A309997. (It will be a draft until approved.)
    $endgroup$
    – Peter Kagey
    11 hours ago














17












17








17


1



$begingroup$


This code challenge will have you compute the number of ways to reach $n$ starting from $2$ using maps of the form $x mapsto x + x^j$ (with $j$ a non-negative integer), and doing so in the minimum number of steps.



(Note, this is related to OEIS sequence A307092.)



Example



So for example, $f(13) = 2$ because three maps are required, and there are two distinct sequences of three maps that will send $2$ to $13$:



$$begin{array}{c} x mapsto x + x^0 \ x mapsto x + x^2 \ x mapsto x + x^0end{array} qquad textrm{or} qquad begin{array}{c}x mapsto x + x^2 \ x mapsto x + x^1 \ x mapsto x + x^0end{array}$$



Resulting in $2 to 3 to 12 to 13$ or $2 to 6 to 12 to 13$.



Example values



f(2)   = 1 (via [])
f(3) = 1 (via [0])
f(4) = 1 (via [1])
f(5) = 1 (via [1,0])
f(12) = 2 (via [0,2] or [2,1])
f(13) = 2 (via [0,2,0] or [2,1,0], shown above)
f(19) = 1 (via [4,0])
f(20) = 2 (via [1,2] or [3,1])
f(226) = 3 (via [2,0,2,1,0,1], [3,2,0,0,0,1], or [2,3,0,0,0,0])
f(372) = 4 (via [3,0,1,0,1,1,0,1,1], [1,1,0,2,0,0,0,1,1], [0,2,0,2,0,0,0,0,1], or [2,1,0,2,0,0,0,0,1])


Challenge



The challenge is to produce a program which takes an integer $n ge 2$ as an input, and outputs the number of distinct paths from $2$ to $n$ via a minimal number of maps of the form $x mapsto x + x^j$.



This is code-golf, so fewest bytes wins.










share|improve this question











$endgroup$




This code challenge will have you compute the number of ways to reach $n$ starting from $2$ using maps of the form $x mapsto x + x^j$ (with $j$ a non-negative integer), and doing so in the minimum number of steps.



(Note, this is related to OEIS sequence A307092.)



Example



So for example, $f(13) = 2$ because three maps are required, and there are two distinct sequences of three maps that will send $2$ to $13$:



$$begin{array}{c} x mapsto x + x^0 \ x mapsto x + x^2 \ x mapsto x + x^0end{array} qquad textrm{or} qquad begin{array}{c}x mapsto x + x^2 \ x mapsto x + x^1 \ x mapsto x + x^0end{array}$$



Resulting in $2 to 3 to 12 to 13$ or $2 to 6 to 12 to 13$.



Example values



f(2)   = 1 (via [])
f(3) = 1 (via [0])
f(4) = 1 (via [1])
f(5) = 1 (via [1,0])
f(12) = 2 (via [0,2] or [2,1])
f(13) = 2 (via [0,2,0] or [2,1,0], shown above)
f(19) = 1 (via [4,0])
f(20) = 2 (via [1,2] or [3,1])
f(226) = 3 (via [2,0,2,1,0,1], [3,2,0,0,0,1], or [2,3,0,0,0,0])
f(372) = 4 (via [3,0,1,0,1,1,0,1,1], [1,1,0,2,0,0,0,1,1], [0,2,0,2,0,0,0,0,1], or [2,1,0,2,0,0,0,0,1])


Challenge



The challenge is to produce a program which takes an integer $n ge 2$ as an input, and outputs the number of distinct paths from $2$ to $n$ via a minimal number of maps of the form $x mapsto x + x^j$.



This is code-golf, so fewest bytes wins.







code-golf sequence combinatorics






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 5 hours ago









xnor

98.3k19 gold badges202 silver badges461 bronze badges




98.3k19 gold badges202 silver badges461 bronze badges










asked 23 hours ago









Peter KageyPeter Kagey

9071 gold badge7 silver badges25 bronze badges




9071 gold badge7 silver badges25 bronze badges











  • 1




    $begingroup$
    I think it should be explicitly noted that the ^ symbol denotes exponentiation. It could be XOR as well (for instance C uses ^ for bitwise XOR).
    $endgroup$
    – Ramillies
    17 hours ago






  • 1




    $begingroup$
    @Ramillies Maybe it should be changed to MathJax. I.e. $x=x+x^j$ instead of x -> x + x^j.
    $endgroup$
    – Kevin Cruijssen
    17 hours ago










  • $begingroup$
    @KevinCruijssen: Good point, that would certainly help.
    $endgroup$
    – Ramillies
    17 hours ago










  • $begingroup$
    I have added this to the OEIS as A309997. (It will be a draft until approved.)
    $endgroup$
    – Peter Kagey
    11 hours ago














  • 1




    $begingroup$
    I think it should be explicitly noted that the ^ symbol denotes exponentiation. It could be XOR as well (for instance C uses ^ for bitwise XOR).
    $endgroup$
    – Ramillies
    17 hours ago






  • 1




    $begingroup$
    @Ramillies Maybe it should be changed to MathJax. I.e. $x=x+x^j$ instead of x -> x + x^j.
    $endgroup$
    – Kevin Cruijssen
    17 hours ago










  • $begingroup$
    @KevinCruijssen: Good point, that would certainly help.
    $endgroup$
    – Ramillies
    17 hours ago










  • $begingroup$
    I have added this to the OEIS as A309997. (It will be a draft until approved.)
    $endgroup$
    – Peter Kagey
    11 hours ago








1




1




$begingroup$
I think it should be explicitly noted that the ^ symbol denotes exponentiation. It could be XOR as well (for instance C uses ^ for bitwise XOR).
$endgroup$
– Ramillies
17 hours ago




$begingroup$
I think it should be explicitly noted that the ^ symbol denotes exponentiation. It could be XOR as well (for instance C uses ^ for bitwise XOR).
$endgroup$
– Ramillies
17 hours ago




1




1




$begingroup$
@Ramillies Maybe it should be changed to MathJax. I.e. $x=x+x^j$ instead of x -> x + x^j.
$endgroup$
– Kevin Cruijssen
17 hours ago




$begingroup$
@Ramillies Maybe it should be changed to MathJax. I.e. $x=x+x^j$ instead of x -> x + x^j.
$endgroup$
– Kevin Cruijssen
17 hours ago












$begingroup$
@KevinCruijssen: Good point, that would certainly help.
$endgroup$
– Ramillies
17 hours ago




$begingroup$
@KevinCruijssen: Good point, that would certainly help.
$endgroup$
– Ramillies
17 hours ago












$begingroup$
I have added this to the OEIS as A309997. (It will be a draft until approved.)
$endgroup$
– Peter Kagey
11 hours ago




$begingroup$
I have added this to the OEIS as A309997. (It will be a draft until approved.)
$endgroup$
– Peter Kagey
11 hours ago










9 Answers
9






active

oldest

votes


















5













$begingroup$

JavaScript (ES6),  111 ... 84  80 bytes



Returns true rather than $1$ for $n=2$.





f=(n,j)=>(g=(i,x,e=1)=>i?e>n?g(i-1,x):g(i-1,x+e)+g(i,x,e*x):x==n)(j,2)||f(n,-~j)


Try it online!



Commented



f = (                     // f is the main recursive function taking:
n, // n = input
j // j = maximum number of steps
) => ( //
g = ( // g is another recursive function taking:
i, // i = number of remaining steps
x, // x = current sum
e = 1 // e = current exponentiated part
) => //
i ? // if there's still at least one step to go:
e > n ? // if e is greater than n:
// add the result of a recursive call with:
g(i - 1, x) // i - 1, x unchanged and e = 1
: // else:
// add the sum of recursive calls with:
g(i - 1, x + e) + // i - 1, x + e and e = 1
g(i, x, e * x) // i unchanged, x unchanged and e = e * x
: // else:
x == n // stop recursion; return 1 if x = n
)(j, 2) // initial call to g with i = j and x = 2
|| f(n, -~j) // if it fails, try again with j + 1





share|improve this answer











$endgroup$























    3













    $begingroup$


    05AB1E, 17 bytes



    2¸[˜DIå#εIÝmy+]I¢


    Try it online!






    share|improve this answer









    $endgroup$























      2













      $begingroup$


      Haskell, 78 75 bytes



      This implementation uses a breath-first-search in the "tree" of iteratively all necessary mappings x -> x + x^j.





      j#x=x+x^j
      f n=[sum[1|x<-l,x==n]|l<-iterate((#)<$>[0..n]<*>)[2],n`elem`l]!!0


      Try it online!



      Explanation



      -- computes the mapping x -> x + x^j
      j#x=x+x^j
      --iteratively apply this function for all exponents [0,1,...,n] (for all previous values, starting with the only value [2])
      iterate((#)<$>[0..n]<*>)[2]
      -- find each iteration where our target number occurs
      [ |l<-...........................,n`elem`l]
      -- find how many times it occurs
      sum [1|x<-l,x==n]
      -- pick the first entry
      f n=.............................................................!!0





      share|improve this answer











      $endgroup$























        2













        $begingroup$


        Python 2, 72 bytes





        f=lambda n,l=[2]:l.count(n)or f(n,[x+x**j for x in l for j in range(n)])


        Try it online!






        share|improve this answer









        $endgroup$















        • $begingroup$
          Nice way of implementing BFS recursively.
          $endgroup$
          – Joel
          3 hours ago



















        1













        $begingroup$

        Perl 5 (-lp), 79 bytes



        $e=$_;@,=(2);@,=map{$x=$_;map$x+$x**$_,0..log($e)/log$x}@,until$_=grep$_==$e,@,


        TIO






        share|improve this answer











        $endgroup$























          1













          $begingroup$

          CJam (27 bytes)



          qi2a{{_W$,f#f+~2}%_W$&!}ge=


          Online demo



          Warning: this gets very memory-intensive very fast.



          Dissection:



          qi            e# Read input and parse to int n (accessed from the bottom of the stack as W$)
          2a e# Start with [2]
          { e# Loop
          { e# Map each integer x in the current list
          _W$,f#f+~ e# to x+x^i for 0 <= i < n
          2 e# and add a bonus 2 for the special case
          }% e# Gather these in the new list
          _W$&! e# Until the list contains an n
          }g
          e= e# Count occurrences


          The bonus 2s (to handle the special case of input 2, because while loops are more expensive than do-while loops) mean that the size of the list grows very fast, and the use of exponents up to n-1 means that the values of the larger numbers in the list grow very fast.






          share|improve this answer









          $endgroup$























            1













            $begingroup$


            Jelly, 16 bytes



            2+*¥þ³Ḷ¤F$n³Ạ$¿ċ


            Try it online!



            A full program taking as its argument $n$ and returning the number of ways to reach $n$ using the minimal path length. Inefficient for larger $n$.






            share|improve this answer









            $endgroup$























              0













              $begingroup$


              Haskell, 65 bytes





              ([2]%)
              l%n|elem n l=sum[1|x<-l,x==n]|1>0=[x+x^k|x<-l,k<-[0..n]]%n


              Try it online!



              Golfing flawr's breadth-first-search. I also tried going backwards from n, but it was longer:



              73 bytes





              q.pure
              q l|elem 2l=sum[1|2<-l]|1>0=q[x|n<-l,x<-[0..n],i<-[0..n],x+x^i==n]


              Try it online!






              share|improve this answer











              $endgroup$























                0













                $begingroup$


                Pyth, 24 bytes



                VQIJ/mu+G^GHd2^U.lQ2NQJB


                Try it online!



                This should produce the correct output, but is very slow (the 372 test case times out on TIO). I could make it shorter by replacing .lQ2 with Q, but this would make the runtime horrendous.



                Note: Produces no output for unreachable numbers $(n leq 1)$



                Explanation



                VQ                        # for N in range(Q (=input)):
                J # J =
                m # map(lambda d:
                u # reduce(lambda G,H:
                +G^GH # G + G^H,
                d2 # d (list), 2 (starting value) ),
                ^U.lQ2N # cartesian_product(range(log(Q, 2)), N)
                / Q # .count(Q)
                IJ JB # if J: print(J); break




                share









                $endgroup$


















                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "200"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f190877%2fcount-the-number-of-shortest-paths-to-n%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  9 Answers
                  9






                  active

                  oldest

                  votes








                  9 Answers
                  9






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  5













                  $begingroup$

                  JavaScript (ES6),  111 ... 84  80 bytes



                  Returns true rather than $1$ for $n=2$.





                  f=(n,j)=>(g=(i,x,e=1)=>i?e>n?g(i-1,x):g(i-1,x+e)+g(i,x,e*x):x==n)(j,2)||f(n,-~j)


                  Try it online!



                  Commented



                  f = (                     // f is the main recursive function taking:
                  n, // n = input
                  j // j = maximum number of steps
                  ) => ( //
                  g = ( // g is another recursive function taking:
                  i, // i = number of remaining steps
                  x, // x = current sum
                  e = 1 // e = current exponentiated part
                  ) => //
                  i ? // if there's still at least one step to go:
                  e > n ? // if e is greater than n:
                  // add the result of a recursive call with:
                  g(i - 1, x) // i - 1, x unchanged and e = 1
                  : // else:
                  // add the sum of recursive calls with:
                  g(i - 1, x + e) + // i - 1, x + e and e = 1
                  g(i, x, e * x) // i unchanged, x unchanged and e = e * x
                  : // else:
                  x == n // stop recursion; return 1 if x = n
                  )(j, 2) // initial call to g with i = j and x = 2
                  || f(n, -~j) // if it fails, try again with j + 1





                  share|improve this answer











                  $endgroup$




















                    5













                    $begingroup$

                    JavaScript (ES6),  111 ... 84  80 bytes



                    Returns true rather than $1$ for $n=2$.





                    f=(n,j)=>(g=(i,x,e=1)=>i?e>n?g(i-1,x):g(i-1,x+e)+g(i,x,e*x):x==n)(j,2)||f(n,-~j)


                    Try it online!



                    Commented



                    f = (                     // f is the main recursive function taking:
                    n, // n = input
                    j // j = maximum number of steps
                    ) => ( //
                    g = ( // g is another recursive function taking:
                    i, // i = number of remaining steps
                    x, // x = current sum
                    e = 1 // e = current exponentiated part
                    ) => //
                    i ? // if there's still at least one step to go:
                    e > n ? // if e is greater than n:
                    // add the result of a recursive call with:
                    g(i - 1, x) // i - 1, x unchanged and e = 1
                    : // else:
                    // add the sum of recursive calls with:
                    g(i - 1, x + e) + // i - 1, x + e and e = 1
                    g(i, x, e * x) // i unchanged, x unchanged and e = e * x
                    : // else:
                    x == n // stop recursion; return 1 if x = n
                    )(j, 2) // initial call to g with i = j and x = 2
                    || f(n, -~j) // if it fails, try again with j + 1





                    share|improve this answer











                    $endgroup$


















                      5














                      5










                      5







                      $begingroup$

                      JavaScript (ES6),  111 ... 84  80 bytes



                      Returns true rather than $1$ for $n=2$.





                      f=(n,j)=>(g=(i,x,e=1)=>i?e>n?g(i-1,x):g(i-1,x+e)+g(i,x,e*x):x==n)(j,2)||f(n,-~j)


                      Try it online!



                      Commented



                      f = (                     // f is the main recursive function taking:
                      n, // n = input
                      j // j = maximum number of steps
                      ) => ( //
                      g = ( // g is another recursive function taking:
                      i, // i = number of remaining steps
                      x, // x = current sum
                      e = 1 // e = current exponentiated part
                      ) => //
                      i ? // if there's still at least one step to go:
                      e > n ? // if e is greater than n:
                      // add the result of a recursive call with:
                      g(i - 1, x) // i - 1, x unchanged and e = 1
                      : // else:
                      // add the sum of recursive calls with:
                      g(i - 1, x + e) + // i - 1, x + e and e = 1
                      g(i, x, e * x) // i unchanged, x unchanged and e = e * x
                      : // else:
                      x == n // stop recursion; return 1 if x = n
                      )(j, 2) // initial call to g with i = j and x = 2
                      || f(n, -~j) // if it fails, try again with j + 1





                      share|improve this answer











                      $endgroup$



                      JavaScript (ES6),  111 ... 84  80 bytes



                      Returns true rather than $1$ for $n=2$.





                      f=(n,j)=>(g=(i,x,e=1)=>i?e>n?g(i-1,x):g(i-1,x+e)+g(i,x,e*x):x==n)(j,2)||f(n,-~j)


                      Try it online!



                      Commented



                      f = (                     // f is the main recursive function taking:
                      n, // n = input
                      j // j = maximum number of steps
                      ) => ( //
                      g = ( // g is another recursive function taking:
                      i, // i = number of remaining steps
                      x, // x = current sum
                      e = 1 // e = current exponentiated part
                      ) => //
                      i ? // if there's still at least one step to go:
                      e > n ? // if e is greater than n:
                      // add the result of a recursive call with:
                      g(i - 1, x) // i - 1, x unchanged and e = 1
                      : // else:
                      // add the sum of recursive calls with:
                      g(i - 1, x + e) + // i - 1, x + e and e = 1
                      g(i, x, e * x) // i unchanged, x unchanged and e = e * x
                      : // else:
                      x == n // stop recursion; return 1 if x = n
                      )(j, 2) // initial call to g with i = j and x = 2
                      || f(n, -~j) // if it fails, try again with j + 1






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 19 hours ago

























                      answered 22 hours ago









                      ArnauldArnauld

                      91.2k7 gold badges107 silver badges372 bronze badges




                      91.2k7 gold badges107 silver badges372 bronze badges




























                          3













                          $begingroup$


                          05AB1E, 17 bytes



                          2¸[˜DIå#εIÝmy+]I¢


                          Try it online!






                          share|improve this answer









                          $endgroup$




















                            3













                            $begingroup$


                            05AB1E, 17 bytes



                            2¸[˜DIå#εIÝmy+]I¢


                            Try it online!






                            share|improve this answer









                            $endgroup$


















                              3














                              3










                              3







                              $begingroup$


                              05AB1E, 17 bytes



                              2¸[˜DIå#εIÝmy+]I¢


                              Try it online!






                              share|improve this answer









                              $endgroup$




                              05AB1E, 17 bytes



                              2¸[˜DIå#εIÝmy+]I¢


                              Try it online!







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 19 hours ago









                              GrimyGrimy

                              5,86915 silver badges30 bronze badges




                              5,86915 silver badges30 bronze badges


























                                  2













                                  $begingroup$


                                  Haskell, 78 75 bytes



                                  This implementation uses a breath-first-search in the "tree" of iteratively all necessary mappings x -> x + x^j.





                                  j#x=x+x^j
                                  f n=[sum[1|x<-l,x==n]|l<-iterate((#)<$>[0..n]<*>)[2],n`elem`l]!!0


                                  Try it online!



                                  Explanation



                                  -- computes the mapping x -> x + x^j
                                  j#x=x+x^j
                                  --iteratively apply this function for all exponents [0,1,...,n] (for all previous values, starting with the only value [2])
                                  iterate((#)<$>[0..n]<*>)[2]
                                  -- find each iteration where our target number occurs
                                  [ |l<-...........................,n`elem`l]
                                  -- find how many times it occurs
                                  sum [1|x<-l,x==n]
                                  -- pick the first entry
                                  f n=.............................................................!!0





                                  share|improve this answer











                                  $endgroup$




















                                    2













                                    $begingroup$


                                    Haskell, 78 75 bytes



                                    This implementation uses a breath-first-search in the "tree" of iteratively all necessary mappings x -> x + x^j.





                                    j#x=x+x^j
                                    f n=[sum[1|x<-l,x==n]|l<-iterate((#)<$>[0..n]<*>)[2],n`elem`l]!!0


                                    Try it online!



                                    Explanation



                                    -- computes the mapping x -> x + x^j
                                    j#x=x+x^j
                                    --iteratively apply this function for all exponents [0,1,...,n] (for all previous values, starting with the only value [2])
                                    iterate((#)<$>[0..n]<*>)[2]
                                    -- find each iteration where our target number occurs
                                    [ |l<-...........................,n`elem`l]
                                    -- find how many times it occurs
                                    sum [1|x<-l,x==n]
                                    -- pick the first entry
                                    f n=.............................................................!!0





                                    share|improve this answer











                                    $endgroup$


















                                      2














                                      2










                                      2







                                      $begingroup$


                                      Haskell, 78 75 bytes



                                      This implementation uses a breath-first-search in the "tree" of iteratively all necessary mappings x -> x + x^j.





                                      j#x=x+x^j
                                      f n=[sum[1|x<-l,x==n]|l<-iterate((#)<$>[0..n]<*>)[2],n`elem`l]!!0


                                      Try it online!



                                      Explanation



                                      -- computes the mapping x -> x + x^j
                                      j#x=x+x^j
                                      --iteratively apply this function for all exponents [0,1,...,n] (for all previous values, starting with the only value [2])
                                      iterate((#)<$>[0..n]<*>)[2]
                                      -- find each iteration where our target number occurs
                                      [ |l<-...........................,n`elem`l]
                                      -- find how many times it occurs
                                      sum [1|x<-l,x==n]
                                      -- pick the first entry
                                      f n=.............................................................!!0





                                      share|improve this answer











                                      $endgroup$




                                      Haskell, 78 75 bytes



                                      This implementation uses a breath-first-search in the "tree" of iteratively all necessary mappings x -> x + x^j.





                                      j#x=x+x^j
                                      f n=[sum[1|x<-l,x==n]|l<-iterate((#)<$>[0..n]<*>)[2],n`elem`l]!!0


                                      Try it online!



                                      Explanation



                                      -- computes the mapping x -> x + x^j
                                      j#x=x+x^j
                                      --iteratively apply this function for all exponents [0,1,...,n] (for all previous values, starting with the only value [2])
                                      iterate((#)<$>[0..n]<*>)[2]
                                      -- find each iteration where our target number occurs
                                      [ |l<-...........................,n`elem`l]
                                      -- find how many times it occurs
                                      sum [1|x<-l,x==n]
                                      -- pick the first entry
                                      f n=.............................................................!!0






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 16 hours ago

























                                      answered 16 hours ago









                                      flawrflawr

                                      29k6 gold badges75 silver badges201 bronze badges




                                      29k6 gold badges75 silver badges201 bronze badges


























                                          2













                                          $begingroup$


                                          Python 2, 72 bytes





                                          f=lambda n,l=[2]:l.count(n)or f(n,[x+x**j for x in l for j in range(n)])


                                          Try it online!






                                          share|improve this answer









                                          $endgroup$















                                          • $begingroup$
                                            Nice way of implementing BFS recursively.
                                            $endgroup$
                                            – Joel
                                            3 hours ago
















                                          2













                                          $begingroup$


                                          Python 2, 72 bytes





                                          f=lambda n,l=[2]:l.count(n)or f(n,[x+x**j for x in l for j in range(n)])


                                          Try it online!






                                          share|improve this answer









                                          $endgroup$















                                          • $begingroup$
                                            Nice way of implementing BFS recursively.
                                            $endgroup$
                                            – Joel
                                            3 hours ago














                                          2














                                          2










                                          2







                                          $begingroup$


                                          Python 2, 72 bytes





                                          f=lambda n,l=[2]:l.count(n)or f(n,[x+x**j for x in l for j in range(n)])


                                          Try it online!






                                          share|improve this answer









                                          $endgroup$




                                          Python 2, 72 bytes





                                          f=lambda n,l=[2]:l.count(n)or f(n,[x+x**j for x in l for j in range(n)])


                                          Try it online!







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered 4 hours ago









                                          xnorxnor

                                          98.3k19 gold badges202 silver badges461 bronze badges




                                          98.3k19 gold badges202 silver badges461 bronze badges















                                          • $begingroup$
                                            Nice way of implementing BFS recursively.
                                            $endgroup$
                                            – Joel
                                            3 hours ago


















                                          • $begingroup$
                                            Nice way of implementing BFS recursively.
                                            $endgroup$
                                            – Joel
                                            3 hours ago
















                                          $begingroup$
                                          Nice way of implementing BFS recursively.
                                          $endgroup$
                                          – Joel
                                          3 hours ago




                                          $begingroup$
                                          Nice way of implementing BFS recursively.
                                          $endgroup$
                                          – Joel
                                          3 hours ago











                                          1













                                          $begingroup$

                                          Perl 5 (-lp), 79 bytes



                                          $e=$_;@,=(2);@,=map{$x=$_;map$x+$x**$_,0..log($e)/log$x}@,until$_=grep$_==$e,@,


                                          TIO






                                          share|improve this answer











                                          $endgroup$




















                                            1













                                            $begingroup$

                                            Perl 5 (-lp), 79 bytes



                                            $e=$_;@,=(2);@,=map{$x=$_;map$x+$x**$_,0..log($e)/log$x}@,until$_=grep$_==$e,@,


                                            TIO






                                            share|improve this answer











                                            $endgroup$


















                                              1














                                              1










                                              1







                                              $begingroup$

                                              Perl 5 (-lp), 79 bytes



                                              $e=$_;@,=(2);@,=map{$x=$_;map$x+$x**$_,0..log($e)/log$x}@,until$_=grep$_==$e,@,


                                              TIO






                                              share|improve this answer











                                              $endgroup$



                                              Perl 5 (-lp), 79 bytes



                                              $e=$_;@,=(2);@,=map{$x=$_;map$x+$x**$_,0..log($e)/log$x}@,until$_=grep$_==$e,@,


                                              TIO







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited 17 hours ago

























                                              answered 17 hours ago









                                              Nahuel FouilleulNahuel Fouilleul

                                              3,9771 gold badge4 silver badges14 bronze badges




                                              3,9771 gold badge4 silver badges14 bronze badges


























                                                  1













                                                  $begingroup$

                                                  CJam (27 bytes)



                                                  qi2a{{_W$,f#f+~2}%_W$&!}ge=


                                                  Online demo



                                                  Warning: this gets very memory-intensive very fast.



                                                  Dissection:



                                                  qi            e# Read input and parse to int n (accessed from the bottom of the stack as W$)
                                                  2a e# Start with [2]
                                                  { e# Loop
                                                  { e# Map each integer x in the current list
                                                  _W$,f#f+~ e# to x+x^i for 0 <= i < n
                                                  2 e# and add a bonus 2 for the special case
                                                  }% e# Gather these in the new list
                                                  _W$&! e# Until the list contains an n
                                                  }g
                                                  e= e# Count occurrences


                                                  The bonus 2s (to handle the special case of input 2, because while loops are more expensive than do-while loops) mean that the size of the list grows very fast, and the use of exponents up to n-1 means that the values of the larger numbers in the list grow very fast.






                                                  share|improve this answer









                                                  $endgroup$




















                                                    1













                                                    $begingroup$

                                                    CJam (27 bytes)



                                                    qi2a{{_W$,f#f+~2}%_W$&!}ge=


                                                    Online demo



                                                    Warning: this gets very memory-intensive very fast.



                                                    Dissection:



                                                    qi            e# Read input and parse to int n (accessed from the bottom of the stack as W$)
                                                    2a e# Start with [2]
                                                    { e# Loop
                                                    { e# Map each integer x in the current list
                                                    _W$,f#f+~ e# to x+x^i for 0 <= i < n
                                                    2 e# and add a bonus 2 for the special case
                                                    }% e# Gather these in the new list
                                                    _W$&! e# Until the list contains an n
                                                    }g
                                                    e= e# Count occurrences


                                                    The bonus 2s (to handle the special case of input 2, because while loops are more expensive than do-while loops) mean that the size of the list grows very fast, and the use of exponents up to n-1 means that the values of the larger numbers in the list grow very fast.






                                                    share|improve this answer









                                                    $endgroup$


















                                                      1














                                                      1










                                                      1







                                                      $begingroup$

                                                      CJam (27 bytes)



                                                      qi2a{{_W$,f#f+~2}%_W$&!}ge=


                                                      Online demo



                                                      Warning: this gets very memory-intensive very fast.



                                                      Dissection:



                                                      qi            e# Read input and parse to int n (accessed from the bottom of the stack as W$)
                                                      2a e# Start with [2]
                                                      { e# Loop
                                                      { e# Map each integer x in the current list
                                                      _W$,f#f+~ e# to x+x^i for 0 <= i < n
                                                      2 e# and add a bonus 2 for the special case
                                                      }% e# Gather these in the new list
                                                      _W$&! e# Until the list contains an n
                                                      }g
                                                      e= e# Count occurrences


                                                      The bonus 2s (to handle the special case of input 2, because while loops are more expensive than do-while loops) mean that the size of the list grows very fast, and the use of exponents up to n-1 means that the values of the larger numbers in the list grow very fast.






                                                      share|improve this answer









                                                      $endgroup$



                                                      CJam (27 bytes)



                                                      qi2a{{_W$,f#f+~2}%_W$&!}ge=


                                                      Online demo



                                                      Warning: this gets very memory-intensive very fast.



                                                      Dissection:



                                                      qi            e# Read input and parse to int n (accessed from the bottom of the stack as W$)
                                                      2a e# Start with [2]
                                                      { e# Loop
                                                      { e# Map each integer x in the current list
                                                      _W$,f#f+~ e# to x+x^i for 0 <= i < n
                                                      2 e# and add a bonus 2 for the special case
                                                      }% e# Gather these in the new list
                                                      _W$&! e# Until the list contains an n
                                                      }g
                                                      e= e# Count occurrences


                                                      The bonus 2s (to handle the special case of input 2, because while loops are more expensive than do-while loops) mean that the size of the list grows very fast, and the use of exponents up to n-1 means that the values of the larger numbers in the list grow very fast.







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered 14 hours ago









                                                      Peter TaylorPeter Taylor

                                                      40.8k4 gold badges57 silver badges150 bronze badges




                                                      40.8k4 gold badges57 silver badges150 bronze badges


























                                                          1













                                                          $begingroup$


                                                          Jelly, 16 bytes



                                                          2+*¥þ³Ḷ¤F$n³Ạ$¿ċ


                                                          Try it online!



                                                          A full program taking as its argument $n$ and returning the number of ways to reach $n$ using the minimal path length. Inefficient for larger $n$.






                                                          share|improve this answer









                                                          $endgroup$




















                                                            1













                                                            $begingroup$


                                                            Jelly, 16 bytes



                                                            2+*¥þ³Ḷ¤F$n³Ạ$¿ċ


                                                            Try it online!



                                                            A full program taking as its argument $n$ and returning the number of ways to reach $n$ using the minimal path length. Inefficient for larger $n$.






                                                            share|improve this answer









                                                            $endgroup$


















                                                              1














                                                              1










                                                              1







                                                              $begingroup$


                                                              Jelly, 16 bytes



                                                              2+*¥þ³Ḷ¤F$n³Ạ$¿ċ


                                                              Try it online!



                                                              A full program taking as its argument $n$ and returning the number of ways to reach $n$ using the minimal path length. Inefficient for larger $n$.






                                                              share|improve this answer









                                                              $endgroup$




                                                              Jelly, 16 bytes



                                                              2+*¥þ³Ḷ¤F$n³Ạ$¿ċ


                                                              Try it online!



                                                              A full program taking as its argument $n$ and returning the number of ways to reach $n$ using the minimal path length. Inefficient for larger $n$.







                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered 12 hours ago









                                                              Nick KennedyNick Kennedy

                                                              6,1371 gold badge9 silver badges15 bronze badges




                                                              6,1371 gold badge9 silver badges15 bronze badges


























                                                                  0













                                                                  $begingroup$


                                                                  Haskell, 65 bytes





                                                                  ([2]%)
                                                                  l%n|elem n l=sum[1|x<-l,x==n]|1>0=[x+x^k|x<-l,k<-[0..n]]%n


                                                                  Try it online!



                                                                  Golfing flawr's breadth-first-search. I also tried going backwards from n, but it was longer:



                                                                  73 bytes





                                                                  q.pure
                                                                  q l|elem 2l=sum[1|2<-l]|1>0=q[x|n<-l,x<-[0..n],i<-[0..n],x+x^i==n]


                                                                  Try it online!






                                                                  share|improve this answer











                                                                  $endgroup$




















                                                                    0













                                                                    $begingroup$


                                                                    Haskell, 65 bytes





                                                                    ([2]%)
                                                                    l%n|elem n l=sum[1|x<-l,x==n]|1>0=[x+x^k|x<-l,k<-[0..n]]%n


                                                                    Try it online!



                                                                    Golfing flawr's breadth-first-search. I also tried going backwards from n, but it was longer:



                                                                    73 bytes





                                                                    q.pure
                                                                    q l|elem 2l=sum[1|2<-l]|1>0=q[x|n<-l,x<-[0..n],i<-[0..n],x+x^i==n]


                                                                    Try it online!






                                                                    share|improve this answer











                                                                    $endgroup$


















                                                                      0














                                                                      0










                                                                      0







                                                                      $begingroup$


                                                                      Haskell, 65 bytes





                                                                      ([2]%)
                                                                      l%n|elem n l=sum[1|x<-l,x==n]|1>0=[x+x^k|x<-l,k<-[0..n]]%n


                                                                      Try it online!



                                                                      Golfing flawr's breadth-first-search. I also tried going backwards from n, but it was longer:



                                                                      73 bytes





                                                                      q.pure
                                                                      q l|elem 2l=sum[1|2<-l]|1>0=q[x|n<-l,x<-[0..n],i<-[0..n],x+x^i==n]


                                                                      Try it online!






                                                                      share|improve this answer











                                                                      $endgroup$




                                                                      Haskell, 65 bytes





                                                                      ([2]%)
                                                                      l%n|elem n l=sum[1|x<-l,x==n]|1>0=[x+x^k|x<-l,k<-[0..n]]%n


                                                                      Try it online!



                                                                      Golfing flawr's breadth-first-search. I also tried going backwards from n, but it was longer:



                                                                      73 bytes





                                                                      q.pure
                                                                      q l|elem 2l=sum[1|2<-l]|1>0=q[x|n<-l,x<-[0..n],i<-[0..n],x+x^i==n]


                                                                      Try it online!







                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited 4 hours ago

























                                                                      answered 4 hours ago









                                                                      xnorxnor

                                                                      98.3k19 gold badges202 silver badges461 bronze badges




                                                                      98.3k19 gold badges202 silver badges461 bronze badges


























                                                                          0













                                                                          $begingroup$


                                                                          Pyth, 24 bytes



                                                                          VQIJ/mu+G^GHd2^U.lQ2NQJB


                                                                          Try it online!



                                                                          This should produce the correct output, but is very slow (the 372 test case times out on TIO). I could make it shorter by replacing .lQ2 with Q, but this would make the runtime horrendous.



                                                                          Note: Produces no output for unreachable numbers $(n leq 1)$



                                                                          Explanation



                                                                          VQ                        # for N in range(Q (=input)):
                                                                          J # J =
                                                                          m # map(lambda d:
                                                                          u # reduce(lambda G,H:
                                                                          +G^GH # G + G^H,
                                                                          d2 # d (list), 2 (starting value) ),
                                                                          ^U.lQ2N # cartesian_product(range(log(Q, 2)), N)
                                                                          / Q # .count(Q)
                                                                          IJ JB # if J: print(J); break




                                                                          share









                                                                          $endgroup$




















                                                                            0













                                                                            $begingroup$


                                                                            Pyth, 24 bytes



                                                                            VQIJ/mu+G^GHd2^U.lQ2NQJB


                                                                            Try it online!



                                                                            This should produce the correct output, but is very slow (the 372 test case times out on TIO). I could make it shorter by replacing .lQ2 with Q, but this would make the runtime horrendous.



                                                                            Note: Produces no output for unreachable numbers $(n leq 1)$



                                                                            Explanation



                                                                            VQ                        # for N in range(Q (=input)):
                                                                            J # J =
                                                                            m # map(lambda d:
                                                                            u # reduce(lambda G,H:
                                                                            +G^GH # G + G^H,
                                                                            d2 # d (list), 2 (starting value) ),
                                                                            ^U.lQ2N # cartesian_product(range(log(Q, 2)), N)
                                                                            / Q # .count(Q)
                                                                            IJ JB # if J: print(J); break




                                                                            share









                                                                            $endgroup$


















                                                                              0














                                                                              0










                                                                              0







                                                                              $begingroup$


                                                                              Pyth, 24 bytes



                                                                              VQIJ/mu+G^GHd2^U.lQ2NQJB


                                                                              Try it online!



                                                                              This should produce the correct output, but is very slow (the 372 test case times out on TIO). I could make it shorter by replacing .lQ2 with Q, but this would make the runtime horrendous.



                                                                              Note: Produces no output for unreachable numbers $(n leq 1)$



                                                                              Explanation



                                                                              VQ                        # for N in range(Q (=input)):
                                                                              J # J =
                                                                              m # map(lambda d:
                                                                              u # reduce(lambda G,H:
                                                                              +G^GH # G + G^H,
                                                                              d2 # d (list), 2 (starting value) ),
                                                                              ^U.lQ2N # cartesian_product(range(log(Q, 2)), N)
                                                                              / Q # .count(Q)
                                                                              IJ JB # if J: print(J); break




                                                                              share









                                                                              $endgroup$




                                                                              Pyth, 24 bytes



                                                                              VQIJ/mu+G^GHd2^U.lQ2NQJB


                                                                              Try it online!



                                                                              This should produce the correct output, but is very slow (the 372 test case times out on TIO). I could make it shorter by replacing .lQ2 with Q, but this would make the runtime horrendous.



                                                                              Note: Produces no output for unreachable numbers $(n leq 1)$



                                                                              Explanation



                                                                              VQ                        # for N in range(Q (=input)):
                                                                              J # J =
                                                                              m # map(lambda d:
                                                                              u # reduce(lambda G,H:
                                                                              +G^GH # G + G^H,
                                                                              d2 # d (list), 2 (starting value) ),
                                                                              ^U.lQ2N # cartesian_product(range(log(Q, 2)), N)
                                                                              / Q # .count(Q)
                                                                              IJ JB # if J: print(J); break





                                                                              share











                                                                              share


                                                                              share










                                                                              answered 6 mins ago









                                                                              ar4093ar4093

                                                                              1915 bronze badges




                                                                              1915 bronze badges

































                                                                                  draft saved

                                                                                  draft discarded




















































                                                                                  If this is an answer to a challenge…




                                                                                  • …Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.


                                                                                  • …Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
                                                                                    Explanations of your answer make it more interesting to read and are very much encouraged.


                                                                                  • …Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.



                                                                                  More generally…




                                                                                  • …Please make sure to answer the question and provide sufficient detail.


                                                                                  • …Avoid asking for help, clarification or responding to other answers (use comments instead).





                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function () {
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f190877%2fcount-the-number-of-shortest-paths-to-n%23new-answer', 'question_page');
                                                                                  }
                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                                                                                  Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                                                                                  Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...