51
\$\begingroup\$

Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[a,b]\$; that is, the product of the range between \$a\$ and \$b\$. You may take \$a\$ and \$b\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \$a\$ will always be less than \$b\$.

Note that the end may be exclusive or inclusive of \$b\$. I'm not picky. ^_^

Test cases

[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24

This is a , so the shortest program in bytes wins.


Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=66202,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
4
  • 2
    \$\begingroup\$ I'm answering this in TI-BASIC tomorrow. \$\endgroup\$ Dec 10, 2015 at 2:48
  • \$\begingroup\$ @SuperJedi224 Good luck ;) \$\endgroup\$ Dec 10, 2015 at 2:48
  • \$\begingroup\$ Can the input be taken as b, a? \$\endgroup\$
    – FlipTack
    Feb 12, 2017 at 20:01
  • \$\begingroup\$ @FlipTack yes you can \$\endgroup\$ Feb 12, 2017 at 20:03

123 Answers 123

1
\$\begingroup\$

JavaScript (using external library) (31 bytes)

 (a,b)=>_.RangeTo(a,b).Product()

Link to lib: https://github.com/mvegh1/Enumerable/

Explanation of code: Anonymous method accepts low bound and high bound for range, and uses built in .Product method to produce the product for that range

enter image description here

\$\endgroup\$
1
\$\begingroup\$

C#, 56 Bytes

int f(int a,int b){var r=1;for(;a<b;a++)r*=a;return r;}
\$\endgroup\$
1
\$\begingroup\$

Excel, 37 bytes

=PRODUCT(A2-ROW(OFFSET(A1,,,A2-A1)))

Data will be a in A1 and b in A2.

The above should be entered as an array formula (ctrl_shift_enter) in any other cell. The result is exclusive of b.

\$\endgroup\$
1
\$\begingroup\$

Pushy, 8 bytes

Non-competing as the language postdates the challenge.

w-:&h;P#

Try it online!

Most of the code is building the range, as there is a builtin for finding the product (P).

w          \ Mirror stack, yielding [a, b, a]
 -         \ Pop (b, a) and push b - a, the difference
  :  ;     \ That many times do:
   &h      \   Push last item +1
      P#   \ Print product

The w-:&h; is essentially a long-winded binary range function, as Pushy only has unary range commands.

\$\endgroup\$
0
1
\$\begingroup\$

JavaScript (ES6), 25 bytes

f=(a,b)=>a-b?a*f(a+1,b):b

Inclusive.

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 14 bytes

{[*] [...] @_}

Try it online!

Reduce the two inputs by range, then reduces by multiplication.

\$\endgroup\$
1
\$\begingroup\$

Triangular, 21 20 bytes

$\S=t$iUprP%..%/*U:<

Try it online!

Takes input with order b, a from standard in.

Ungolfed: (Explanation to be added later)

      $ 
     \ S 
    = t $ 
   i U p r 
  P % . . % 
 / * U : <


Previous Version (21 bytes):

1\P\p$?Ud$=0%)(/P*U:<
\$\endgroup\$
1
\$\begingroup\$

GolfScript, 8 bytes

Idea copied from the gs2 solution.

~,\>{*}*

Try it online!

Explanation

~        # Dump the input,            e.g. 2 4
 ,       # Generate range from 0 to input: 2 [0 1 2 3 4]
  \      # Swap the stack                : [0 1 2 3 4] 2
   >     # Keep all those that are larger: [2 3 4]
    {*}* # Reduce by multiplication      : 24
\$\endgroup\$
1
  • \$\begingroup\$ The \ is not necessary and this does not work with negative numbers. \$\endgroup\$
    – 2014MELO03
    Oct 12, 2020 at 18:09
1
\$\begingroup\$

Gol><>, 13 bytes

I::I-F$M:@*|h

Try it online!

Takes b then a from stdin, and uses inclusive range.

How it works

I::I-F$M:@*|h

I::I-           Take b, duplicate twice, take a, subtract
                [b b b-a]
     F     |    Repeat b-a times:
                [counter product]
      $M          Swap two, decrement counter
                  [product counter-1]
        :@        Duplicate, rotate 3
                  [counter-1 counter-1 product]
          *       Multiply
                  [counter-1 product']
            h   Print top as number and exit
\$\endgroup\$
1
\$\begingroup\$

C# (Visual C# Interactive Compiler), 37 bytes

int f(int a,int b)=>a<b?a*f(a+1,b):b;

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Javascript

f=(a,b)=>a>b||a*f(a+1,b)

or

f=(a,b)=>[...Array(b-a).keys()].map(i=>i+a).reduce((a,b)=>a*b)

Python

f=lambda a,b:reduce(lambda x,y:x*y,range(a,b))
\$\endgroup\$
1
\$\begingroup\$

Arn, 5 bytes

ë|¶Ý║

Try it!

Explained

Unpacked: *\(=>\

  \           Fold with
*             Multiplication
    (         Begin expression
        \     Fold with
      =>      Inclusive range
          _   Variable initialized to STDIN; implied
    )         End expression; implied

The power of the fold operator, alternatives would be *\=>?1 or *\=>:} (hypothetically, for some reason they are broken as of typing this. Trying to fix).

\$\endgroup\$
1
\$\begingroup\$

Scala, 9 bytes

_.product

Try it in Scastie

Accepts input as a Range object (inclusive or exclusive).

\$\endgroup\$
1
\$\begingroup\$

O, 12 bytes

[j:v,;]jv-+*

Try it online!

[j:v            Input and save to v without popping
    ,;          Range (1..n inclusive)
      ]jv-      Range end - start
          +     Add it vectorised with range
           *    Product
\$\endgroup\$
1
\$\begingroup\$

x86-16 machine code, 10 bytes

00000000: 8bc8 f7eb 4b3b d97f f9c3                 ....K;....

Listing:

8B C8       MOV  CX, AX         ; running product start at a 
        MUL_LOOP: 
F7 EB       IMUL BX             ; multiply running product by b 
4B          DEC  BX             ; decrement b
3B D9       CMP  BX, CX         ; is b > a?
7F F9       JG   MUL_LOOP       ; if so, go forth and multiply
C3          RET                 ; return to caller

Input a in AX, b in BX, inclusive of b. Output to AX.

Tests using DOS DEBUG:

enter image description here

Note: before anyone asks... you cannot use LOOPNZ to decrement and compare a and b. In the case where input a (CX) is 0, it will end the loop before multiplying by the value of a, so no good.

\$\endgroup\$
1
\$\begingroup\$

Husk, 2 bytes

Π…

Try it online!

   # arguments (² => second last argument & ⁰ => last argument) are implicit
 … # inclusive numeric range
Π… # product of list
\$\endgroup\$
1
\$\begingroup\$

dc, 23 bytes

dsc[lc1+dsc*lclb>g]dsgx

Takes input with the upper bound (inclusive) in register b and the lower bound (inclusive) at the top of the stack. Returns the answer at the top of the stack.

Uses register c a lot, so removing that would save a lot of bytes. Basically it's just a for-loop.

Run as:

{UPPER_BOUND}sb{LOWER_BOUND} dsc[lc1+dsc*lclb>g]dsgx p
\$\endgroup\$
1
\$\begingroup\$

Nim, 47 bytes

proc f(a,b,c:var int)=
  c=1;for i in a..b:c*=i

Attempt This Online!

All arguments must be variables, passed by reference. Return value in third parameter, original value ignored. As usual with Nim, not very small byte count.

\$\endgroup\$
1
\$\begingroup\$

Ly, 23 11 bytes

&nRy[p*y,]p

Try it online!

Let's try not doing it the "hard way" this time... :) The code generates a sequence of numbers on a stack, then works through the stack multiplying entries until there's only one number. When the program ends, that single entry prints as a number automatically.

&nRy[p*y,]p  - 
&n           - read in the two numbers
  R          - generate a range of numbers (inclusive)
   y[p y,]p  - as long as the stack size is 2 or more
      *      - multiply the top two entries
\$\endgroup\$
1
\$\begingroup\$

APL, 12 bytes

{⍺×.-1-⍳⍵-⍺}

Explanation on example of arguments 2 and 5:

⍳⍵-⍺ ⍝ Array of numbers from 1 to ⍵-⍺: 1 2 3
1-   ⍝ Substract the array from 1: 0 ¯1 ¯2
⍺×.- ⍝ Substract the array from ⍺: 2 3 4
     ⍝ Then reduce by multiplication, of course

Mathematical justification: ⍺-(1-x) = (⍺-1)+x

\$\endgroup\$
1
\$\begingroup\$

Nibbles, 2.5 bytes (5 nibbles)

`*>$,

Input is (a,b] (so 5 10 represents the range 6 7 8 9 10).

    ,      # range from 1..(implicit) arg1
  >        # drop first      elements
   $       #            arg2
`*         # product

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Perl 5 -MList::Util=product -p, 16 bytes

$_=product$_..<>

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Knight, 34 bytes

;;;;=xP=yP=p 1W<=x+1x+2y=p*p-x 1Op

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ You should shave a two bytes off by doing =pT (you'd have to not make it the last assignment, though, as it'd conflict with the W), and then doing =p*-xTp. \$\endgroup\$
    – Sampersand
    Aug 14, 2022 at 22:24
1
\$\begingroup\$

Arturo, 12 bytes

$=>[∏&..&]

Try it

\$\endgroup\$
1
\$\begingroup\$

HP48 User RPL,

Input is a and b in the stack.

«
  'X'
  DUP
  4 UNROLL
  UNROT
  1 SEQ
  ∏LIST
»
\$\endgroup\$
1
\$\begingroup\$

Pyt, 2 bytes

ŘΠ

Try it online!

Takes inputs as b, a separated by newlines

\$\endgroup\$
1
\$\begingroup\$

><> (Fish), 29 bytes

&1$:&v
v?=&:<|.!02$*@+1:
>~n;

Try it

\$\endgroup\$
1
\$\begingroup\$

BQN, 7 bytes

×´⊢+↕∘-

Thanks to @ConorO'Brien

Try it

BQN, 10 bytes

{×´𝕨+↕𝕩¬𝕨}

Try it

Uses an inclusive range. This is the first thing I've ever written in BQN and I couldn't figure out how to make it tacit for the life of me. Any tips appreciated. :)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I'm not great at BQN, but I think you have this for 7b (arguments reversed, exclusive at one end): ×´⊢+↕∘- (Try it) \$\endgroup\$ Jun 5, 2023 at 3:16
1
\$\begingroup\$

Pascal, 76 B

Utilizing a recursive definition of the product you may arrive at one of the following solutions:

function p(a,b:integer):integer;begin if a=b then p:=a else p:=a*p(a+1,b)end
function p(a,b:integer):integer;begin if a<b then p:=a*p(a+1,b)else p:=a end
function p(a,b:integer):integer;begin if b>a then p:=a*p(a+1,b)else p:=a end

86 B (standard iterative solution): Pascal’s for-loop limits are inclusive (just like the \$\prod\$ and \$\sum\$ limits in mathematics are inclusive, too). In Standard Pascal (as specified by ISO standard 7185) for-loop counters must fulfill certain eligibility criteria (some dialects may be more lenient with that). Therefore a new variable is declared:

function p(a,b:integer):integer;var i:integer;begin for i:=a+1 to b do a:=a*i;p:=a end
\$\endgroup\$
1
\$\begingroup\$

Itr, 5 bytes

â-º+P

solution for exclusive range

online interpreter

Explantion

â-º+P ; implicit input, stack: [hi low]>
â     ; under -> stack: [low hi low]>
 -    ; subtraction -> stack: [low hi-low]>
  º   ; zero-based range
   +  ; add low to zero based range giving range [low,...hi-1]
    P ; product
      ; implicit output

Itr, 7 bytes

solution for inclusive range

â-1+º+P

2 bytes using the new range built-in

¨P

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.