40
\$\begingroup\$

Your task is simple: given two integers a and b, output ∏[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\$
  • 2
    \$\begingroup\$ I'm answering this in TI-BASIC tomorrow. \$\endgroup\$ – SuperJedi224 Dec 10 '15 at 2:48
  • \$\begingroup\$ @SuperJedi224 Good luck ;) \$\endgroup\$ – Conor O'Brien 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\$ – Conor O'Brien Feb 12 '17 at 20:03

89 Answers 89

1 2
3
1
\$\begingroup\$

Reng v.3, 25 bytes

This is encoded in ISO 8859-1, and you can try it out at the new IO page!

ii#x:1+::xe)2(¿Bh$1¶a*¡n~

Is an inclusive range.

ii takes 2 inputs, and stores the second one (the maximum) in x. :1+:: sets a to a (a+1) (a+1) (a+1). xe sets the TOS to the equality of the counter (a+1) and )2( sets the STOS to 2. ¿ pops two numbers and, if the TOS is true, the pointer moves STOS times. Otherwise, we just go forward. In the event that we have not reached the maximum, Bh goes back 11 units. $ drops the excess counter from the TOS once we are done looping. sets the default pop from an empty stack to 1, so we can use a double-sided mirror loop to multiply everything. a is a one-sided mirror, and * multiplies values. ¡ mirrors until the stack's length is 1. Once the length is 1, n~ is met and outputs the result and exits the program.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Mathcad, 4 "bytes"

Uses the built-in Iterated Product Operator, which is entered from the keyboard by ctl-#. Type k into the iterator and expression placeholders and then type the evaluation operator (=), giving a total of 4 "bytes" where one byte is taken to be the number of characters needed to enter an expression.

enter image description here

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Factor, 79 43 29 bytes

Hooray for auto use!

It's quite elegant, really. A lambda, that goes on the stack.

[ 1 - [a,b] 1 [ * ] reduce ]
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Matricks, 24 bytes

Matricks is a new esolang I invented to deal with matrices. Run like: python matricks.py [[<num1>,<num2>]]

mg:;+c:1:g:1;-g:;;kp{};;

This is a simple answer. Matricks has a built-in for taking the product of an array, p, so all I need to do is make the range with the constructor, m

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

k/kona, 8 bytes

*/a+!b-a

Let's break this down: k reads right-to-left, so:

b-a finds the difference between b and a, to give the number of numbers required

!(b-a) generates a list from 0 to (b-a), giving the range [0, (b-a))

a+(!b-a) adds a to each element of the list, to get the range [a, b)

*/(a+!b-a) applies multiplication over all elements of the list; * is the multiply operator, and / is the over adverb, which is like a map/reduce function, applying its left-hand argument over all elements of its right-hand argument.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Racket (scheme), 29 bytes

Functional programming woot

Apply applies a function to all elements of a list, and range creates a list ranging from a to b. The function being applied is *. Exclusive.

(λ(a b)(apply *(range a b)))
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Fith, 17 bytes (non-competing)

This language was created after the challenge.

{ range product }

Anonymous function. Excludes b. Pretty self-explanatory.

Stack effect: a b -- *[a,b)

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Is this your language? :3 \$\endgroup\$ – Conor O'Brien Jun 27 '16 at 0:31
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Yes it is! Mainly inspired by Factor and Haskell. It's concatenative/stack-based. \$\endgroup\$ – jqblz Jun 27 '16 at 1:02
  • 1
    \$\begingroup\$ I guess then {range would be one token, so the whitespace is necessary? \$\endgroup\$ – Conor O'Brien Jun 27 '16 at 2:03
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Unfortunately, yes. \$\endgroup\$ – jqblz Jun 27 '16 at 3:05
  • \$\begingroup\$ Are you sure it's not just a successor to Forth? :P \$\endgroup\$ – mbomb007 Jul 1 '16 at 21:27
1
\$\begingroup\$

><>, 33 bytes

 1&:@$:@)?\&n;
:$@:+1&*&:/?@@$@)@

My first fish attempt.

Inclusive range
Assumes a and b are on the stack.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 6 - 15 bytes

{[*] $^a..$^b}

Usage:

> {[*] $^a..$^b}(2,5)
120
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Forth, 33 bytes

Pretty simple looping program.

: f DUP ROT DO DUP I * LOOP ; f .

Try it online

| improve this answer | |
\$\endgroup\$
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

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

C#, 56 Bytes

int f(int a,int b){var r=1;for(;a<b;a++)r*=a;return r;}
| improve this answer | |
\$\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.

| improve this answer | |
\$\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.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

tcl, 55

incr p
while \$a<$b {set p [expr $p*$a];incr a}
puts $p

demo

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Java 7, 49 48 bytes

int c(int a,int b){return-~a!=b?a*c(a+1,b):a*b;}

corsiKa's answer is exclusive, mine is inclusive (and slightly shorter by using recursion instead of a loop).

Explanation:

Try it here.

int c(int a,int b){  // Method with two integer parameters and integer return-type
  return-~a!=b?      //  If `a+1` is not equal to `b`
         a*c(a+1,b)  //   Return `a` multiplied by the recursive call with `a+1,b`
        :            //  Else:
         a*b;        //   Return `a*b`
}                    // End of method
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Ahead, 7 bytes

Input is taken as two numbers on standard in. Range is [a,b].

IIEK*O@

II       read two ints and push to stack
  E      expand range between top two stack items
   K     reduce stack by...
    *    multiplying
     O   pop and print number
      @  terminate

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

F# (.NET Core), 27 bytes

fun a b->Seq.fold(*)1[a..b]

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Clam, 5 bytes

p;Brr

Explanation

p     - Print...
 ;    - Product of...
  B   - Range...
   r  - Next input
    r - Next input
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 2, 30 bytes

f=lambda a,b:b<a or a*f(a+1,b)

Try it online!

Range is inclusive (e.g., f(2,5) => 120).

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

JavaScript (ES6), 25 bytes

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

Inclusive.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl 5 -p, 22 bytes

$_=eval join'*',$_..<>

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl 6, 14 bytes

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

Try it online!

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

| improve this answer | |
\$\endgroup\$
0
\$\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:<
| improve this answer | |
\$\endgroup\$
0
\$\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
| improve this answer | |
\$\endgroup\$
0
\$\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!

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Kotlin, 30 bytes

Range is inclusive

{a,b->(a..b).reduce{c,d->c*d}}

Try it online!


Kotlin, 21 bytes

If you can take input as an IntRange:

{it.reduce{c,d->c*d}}

Try it online!

| improve this answer | |
\$\endgroup\$
0
\$\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))
| improve this answer | |
\$\endgroup\$
1 2
3

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.