45
\$\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 '15 at 2:48
  • \$\begingroup\$ @SuperJedi224 Good luck ;) \$\endgroup\$ Dec 10 '15 at 2:48
  • \$\begingroup\$ Can the input be taken as b, a? \$\endgroup\$
    – FlipTack
    Feb 12 '17 at 20:01
  • \$\begingroup\$ @FlipTack yes you can \$\endgroup\$ Feb 12 '17 at 20:03

104 Answers 104

1 2 3
4
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 '20 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\$

Factor + math.unicode, 12 bytes

[ [a,b] Π ]

Try it online!

It's a quotation (anonymous function) that takes 2 integers from the data stack as input and leaves one integer on the data stack as output.

  • [a,b] Create a range from two integers. As you may have guessed, this is inclusive of both. All of the other words are also available, such as [a,b).
  • Π Find the product.
\$\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\$

HBL, 3 bytes

*(0.,

Uses inclusive range. Try it at HBL Online!

Explanation

After parentheses autocompletion, we have '(*(0.,)):

'(*(0.,))
'(      )  Define a function which returns
  *        the product of
   (0  )   the range from
     .     the first argument to
      ,    the second argument
\$\endgroup\$
0
\$\begingroup\$

Charcoal, 20 bytes

≔¹ξNαNβF…αβ«≔×ξιξ»Iξ

Try it online!

Verbose

Assign 1 x
InputNumber a; InputNumber b; 
for(Range a b){
    Assign (Times x i) x
} 
Print Cast x

Try it online!

\$\endgroup\$
0
\$\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\$
0
\$\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\$
0
\$\begingroup\$

Ly, 23 bytes

1nn1[p1IL[ru;]psrl*r,1]

Try it online!

This code uses maintains three entries on a stack, the accumulator value, the "ending" (smaller) number of the range, and the "current" number in the range. It works by decrementing the current number until it's less than the ending number. And each time through the loop it multiplies the accumulator. It computes the product of inclusive range as coded and assumes the range will be given with the smaller number first.

1                       - initialize accumulator entry to 1
 nn                     - read two integer range spec onto the stack
   1[p               1] - infinite loop
      1I                - copy stack entry #1 to the top
        L               - compare top two entries with "less than" op
         [   ]p         - if/then, true is we processed the whole range
          ru;           - print the accumulator value and exit
               s        - save top of stack to backup cell
                r       - reverse stack
                 l*     - load backup cell, multiple top two stack entries
                   r,   - reverse stack, decrement top of stack
\$\endgroup\$
0
\$\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 2 3
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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