46
\$\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

108 Answers 108

3
\$\begingroup\$

Python, 52 bytes

Very simple code; a bit too long.

def p(a,b):
 t=1
 for i in range(a,b):t*=i
 return t
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6), 45 41 bytes

Saved 4 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ

(a,b)=>[...Array(b-a)].reduce(x=>x*a++,1)

Seems a little too long...

(a,b)=>           // Define an anonymous function that takes parameters a and b, and returns:
[...Array(b-a)]   // An array of b-a items,
.reduce(          // Reduced by
x=>x*a++          //  multiplying each item with the previous,
,1)               //  starting at 1.
\$\endgroup\$
3
  • \$\begingroup\$ That works? kudos! I don't think you need the y in the reduce mapping, so cut it off at x=>x*a++ \$\endgroup\$ Dec 10, 2015 at 3:09
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, that trick works really well! \$\endgroup\$ Dec 10, 2015 at 3:11
  • 2
    \$\begingroup\$ you should add a semicolon at the end. for the score. \$\endgroup\$
    – Seadrus
    Dec 10, 2015 at 3:11
3
\$\begingroup\$

Perl 6, 14 bytes

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

usage:

my &code = {[*] $^a..$^b}
say code |$_ for (2,5),(5,10),(-4,3),(0,3),(-4,-1);
# 120
# 151200
# 0
# 0
# 24

say chars code 1,10000;
# 35660

If you wanted to exclude the last element use ..^ instead of ..

\$\endgroup\$
3
\$\begingroup\$

gs2, 4 bytes

Hex: 57 0e 4f 65

Mnemonics: read-nums dump crange product

Try it online!

dump pops a list from the stack and pushes its contents (like ~ in GolfScript), and crange gives [a,b).

\$\endgroup\$
0
3
\$\begingroup\$

Java 7, 54 characters

int p(int a,int b){int p=a;while(++a<b)p*=a;return p;}

We cheat the first multiply by assigning it to the temp-product. Then we pre-increment the counter (shamelessly stolen from the input parameter) to skip the first one.

Compare < b instead of <= b - both are to spec, but this saves a character.

Sample:

C:\files>type BadProd.java
class BadProd {
    public static void main(String...args) {
        System.out.println(p(2,5));
        System.out.println(p(5,10));
        System.out.println(p(-4,3));
        System.out.println(p(0,3));
        System.out.println(p(-4,0));

    }
    static int p(int a,int b){int p=a;while(++a<b)p*=a;return p;}
}
C:\files>java BadProd
24
15120
0
0
24
\$\endgroup\$
3
  • \$\begingroup\$ 43 bytes if you use a lambda: (a,b)->{int p=a;while(++a<b)p*=a;return p;} \$\endgroup\$
    – GamrCorps
    Dec 11, 2015 at 0:40
  • \$\begingroup\$ Currently on Java 7 - updated to clarify. Good point though! \$\endgroup\$
    – corsiKa
    Dec 11, 2015 at 0:42
  • \$\begingroup\$ Came here to create a Java 7 answer, but you beat me to it. :) I noticed yours is exclusive b and uses a loop though, so I made a (slightly shorter) inclusive b method using recursion. Cool to see more code-golfing Java 7 answers, even though you've answered this more than halve a year ago. ;) +1 from me. \$\endgroup\$ Jun 8, 2016 at 11:37
3
\$\begingroup\$

dc, 41 38 37 bytes

This is my first code golf, so bear with me

[lad1+sa*dstlalb>d]sd?sbdst1+saltldxf

It must be saved as a file, and invoked (with bash, so UNIX only) as

dc -f [filename]

It will proceed to wait for input, in the form of a b integers. Note that negative numbers must come as _number.


Alternatively,

echo "X Y [lad1+sa*dstlalb>d]sd?sbdst1+saltdxf" | dc

with X and Y replaced with the two numbers you'd like to product-over-range. This one won't wait unless you don't pipe two numbers.


Explanation:

The recursive macro:
[lad    # load the contents of register a onto the stack, and duplicate it
 1+sa   # Add 1 to the top of the stack (a) and store it in register a
 *dst   # Multiply two off the stack, duplicate and store in register t (stack contains t)
 lalb>d # load a and b, as long as b>a execute d (which is this macro)
 ]sd    # Store that macro in register d
 ?      # Wait for input, hope it is [a b] without braces 
 sbd    # store b, duplicate a (stack == a a) (old: sbddsa)
 st     # store a => t (stack == a)
 1+sa   # add 1 to a and store it in a
 lt     # load t since d expects the total to be on the stack
 ldx    # load d and execute it as a macro
 f      # after d is done recursively calling, t will still be on the stack.
        # Print the stack and close (close is implicit)

There was a removal of a spare duplication and store (dsa)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I believe you can omit the q, since dc automatically terminates when it reaches the end of its input. \$\endgroup\$
    – Joe
    Jul 24, 2016 at 19:26
  • \$\begingroup\$ By the way, another common input method is dc -e "stuff". This will also take input from stdin or piped in from echo. Keep up the good work! dc is my favourite language. \$\endgroup\$
    – Joe
    Jul 25, 2016 at 19:00
3
\$\begingroup\$

Branch, 26 bytes

Z}N\;^-[n^\z^*Zn}N^\o^-]z#

Try it on the online Branch interpreter!

Z                   Save the value (the first argument) as register Z
}N                  Increment and save to N
\;                  Go to the right child and copy the parent value
^-                  Go to the parent and subtract (the left child is pre-set as the second argument)
[               ]   While non-zero (basically, while N is not the same as the end)
 n                  Restore register N
  ^\z^              Put Z in the right child and go to the parent
      *Z            Multiply and save to Z; these three lines do Z = Z * N
        n}N         Restore N, increment, and save back to N
           ^\o^-    Compare against register O; automatically set to the second argument
z#                  Restore Z, the product, and output

This is right-exclusive.

\$\endgroup\$
2
\$\begingroup\$

Mouse, 36 bytes

?A:?B:A.I:(A.B.<^A.1+A:A.I.*I:)I.!$

This reads two integers from STDIN and prints an integer to STDOUT. This computes the sum over the closed interval, i.e. [a,b] rather than [a,b).

Ungolfed:

? A:             ~ Read an integer from STDIN, assign to A
? B:             ~ Read STDIN, assign B
A. I:            ~ Begin an accumulator at A
( A. B. < ^      ~ While A < B...
  A. 1 + A:      ~ Increment A
  A. I. * I:     ~ I *= A
)
I. !             ~ Print I to STDOUT
$
\$\endgroup\$
2
\$\begingroup\$

zsh, 30 bytes

f=({$1..$2})
echo $[${f// /*}]

Sample run:

manatwork% zsh product.zsh 5 10
151200
\$\endgroup\$
1
2
\$\begingroup\$

JavaScript (ES6), 39

Inclusive range.

(a,b)=>[...Array(b-a)].map(_=>b*=a++)|b

Note: map beats reduce once again

\$\endgroup\$
1
  • \$\begingroup\$ Nice, didn't think of that. +1 \$\endgroup\$ Dec 10, 2015 at 16:05
2
\$\begingroup\$

Fortran, 44 bytes

Finally a use for those pesky implicit types.

function j(k,l)
j=1
do i=k,l
j=j*i
enddo
end

Test program:

program testProduct
  integer :: a, k, l
  k = -4
  l = -1
  a = j(k,l)
  print*,a
end program testProduct
\$\endgroup\$
2
\$\begingroup\$

Vitsy, 14 bytes

Note to self: add range

Expects input as b a.

D{-\[D1+]l1-\*
D               Duplicate the top input.
 {-\[   ]       Repeat the stuff in the brackets by the difference between the 
                inputs.
     D1+        Duplicate, add one.
                I now have the range [a,b].
         l1-\*  Multiply all the items together.

This is a function in Vitsy that will leave the product of the range [a,b] on the stack. "But how do I test it?!?" I hear you ask?

Concatenate N. c:

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 3k rep for you ! :D \$\endgroup\$ Dec 11, 2015 at 12:20
  • \$\begingroup\$ \o/ @CᴏɴᴏʀO'Bʀɪᴇɴ \$\endgroup\$ Dec 11, 2015 at 12:35
2
\$\begingroup\$

dc, 27 bytes

Input assumes a is on top of the main stack and b is under it

dsar[dsc*lc1-dla<A]sAlAxrp

Ungolfed:

dsa        # duplicate 'a', store a copy in register a
r          # reverse top two items on stack
[          # start macro definition 
  dsc      # duplicate counter, store in register c 
           #  ('b' is the initial counter value)
  *        # pop top two elements of stack, multiply and push result
  lc       # copy the stored counter to the stack
  1- d     # decrement and duplicate it
  la       # copy 'a' to the stack
  <A       # if 'a' is < the counter, run macro A
]sA        # store this macro as A
lAx        # execute macro A
r          # reverse top two elements of stack
p          # pop/print the result
\$\endgroup\$
2
\$\begingroup\$

LabVIEW, 14 LabVIEW Primitives

Range is exclusive. Creates an array from a to b then multiplies all elements.

\$\endgroup\$
0
2
\$\begingroup\$

TI-Basic, 14 11 bytes

Prompt A,B:prod(randIntNoRep(A,B
\$\endgroup\$
2
\$\begingroup\$

Milky Way 1.5.17, 28 bytes

1%{¢¢L§{?{¢1-e__^}}£*}!

Explanation

1          1             # push integer to the stack
 %{                £ }   # for loop
   ¢¢     ¢              # read a single line of input from the command line
     L                   # push a Pythonic range(0, TOS + 1)
      §{          }      # mapping
        ?{    __ }       # if-else statement
            -            # subtract the STOS from the TOS
             e           # order the TOS and STOS (greater-than)
                ^        # pop the TOS
                      !  # output the TOS

Usage

$ ./mw <path-to-code> -i <input>

Example:

$ ./mw test.mwg -i "2
5"

Milky Way takes line breaks literally. \n is not interpreted as a line break. In future versions, this will be changed.

\$\endgroup\$
2
\$\begingroup\$

Arcyóu, 17 bytes

(F(a b)(r *(_ a b

This includes a but excludes b.

Explanation:

(F(a b)    ; Anonymous function F(a, b)
  (r *     ; Reduce by multiplication
    (_ a b ; Range from a to b
\$\endgroup\$
2
\$\begingroup\$

Rust, 52 51 bytes

fn p(mut a:i32,b:i32)->i32{for i in a+1..b{a*=i;}a}

Usage (+ ungolfed version) as follows:

fn p(mut a:i32, b:i32) -> i32 {
    for i in a+1..b {
        a *= i;
    }
    a
}

fn main() {
    println!("{}", p(2, 5));
    println!("{}", p(5, 10));
    println!("{}", p(-4, 3));
    println!("{}", p(-4, 0));
}

Uses the current stable version of Rust (1.5.0)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ fn p(a:i32,b:i32)->i32{(a..b).fold(1,|a,b|a*b)}. In a future version of Rust: fn p(a:i32,b:i32)->i32{(a..b).product()}. \$\endgroup\$
    – Shepmaster
    Jan 23, 2016 at 20:19
2
\$\begingroup\$

PlatyPar, 4 bytes

_XF*

_ gets the range [a,b), X expands it onto the stack, and F* folds multiplication over the range. Try it online!

\$\endgroup\$
2
\$\begingroup\$

jq, 36 bytes

(35 characters code + 1 character command line option)

reduce range(.[0];.[1])as$i(1;.*$i)

Sample run:

bash-4.3$ bin/jq -s 'reduce range(.[0];.[1])as$i(1;.*$i)' <<< '5 10'
15120

On-line test (Passing -s through URL is not supported – so input passed as [5, 10].)

\$\endgroup\$
2
\$\begingroup\$

PHP, 42 Bytes

<?=array_product(range($ARGV[1],$ARGV[2]))

<?=                         // Open file, '=' is shorthand for 'echo'
array_product(              // Get product of array
range($argv[1],$argv[2])    // array is range from a to b
)
\$\endgroup\$
2
\$\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)

\$\endgroup\$
6
  • \$\begingroup\$ Is this your language? :3 \$\endgroup\$ Jun 27, 2016 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, 2016 at 1:02
  • 1
    \$\begingroup\$ I guess then {range would be one token, so the whitespace is necessary? \$\endgroup\$ Jun 27, 2016 at 2:03
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Unfortunately, yes. \$\endgroup\$
    – jqblz
    Jun 27, 2016 at 3:05
  • \$\begingroup\$ Are you sure it's not just a successor to Forth? :P \$\endgroup\$
    – mbomb007
    Jul 1, 2016 at 21:27
2
\$\begingroup\$

Swift, 26 58 bytes

func p(a:Int,b:Int)->Int{return(a+1..<b).reduce(a){$0*$1}}
\$\endgroup\$
0
2
\$\begingroup\$

tcl, 55

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

demo

\$\endgroup\$
2
\$\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
\$\endgroup\$
2
\$\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!

\$\endgroup\$
2
\$\begingroup\$

F# (.NET Core), 27 bytes

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Clam, 5 bytes

p;Brr

Explanation

p     - Print...
 ;    - Product of...
  B   - Range...
   r  - Next input
    r - Next input
\$\endgroup\$
2
\$\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).

\$\endgroup\$
2
\$\begingroup\$

Keg -hr, 3 bytes

ɧ∑*

Try it online!

Explanation:

ɧ   # Generate inclusive range from two integer inputs
 ∑* # Calculate product of whole stack
    # Output
\$\endgroup\$
0

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.