22
\$\begingroup\$

Input: Two decimal integers. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their product, as a decimal integer. For example, the input 5 16 would lead to the output 80.

Restrictions: No standard loopholes please. This is , answer in lowest amount of bytes wins.

Notes: Layout stolen from my earlier challenge, Add two numbers.

Test cases:

1 2   -> 2
4 5   -> 20
7 9   -> 63
-2 8  -> -16
8 -9  -> -72
-8 -9 -> 72
0 8   -> 0
0 -8  -> 0
8 0   -> 0
-8 0  -> 0
0 0   -> 0

Or as CSV:

a,b,c
1,2,2
4,5,20
7,9,63
-2,8,-16
8,-9,-72
-8,-9,72
0,8,0
0,-8,0
8,0,0
-8,0,0
0,0,0

Leaderboard

var QUESTION_ID=106182,OVERRIDE_USER=8478;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
    \$\begingroup\$ @FlipTack That's assuming addition and multiplication are as easy in any language, which I don't know if it's actually true. \$\endgroup\$ – Fatalize Jan 9 '17 at 8:13
  • 17
    \$\begingroup\$ I don't think it's fair to allow the "add two numbers" challenge but close this one. Even though it's very trivial in most programming languages, it's still a valid challenge. If this is too broad, then the "add two numbers" challenge must also be too broad. \$\endgroup\$ – Mego Jan 9 '17 at 8:42
  • 33
    \$\begingroup\$ Anyone is free to downvote trivial challenges if they don't like them, but this is a perfectly valid and on-topic challenge and it's nowhere near "too broad" (if anything, you might call a trivial challenge too narrow). I'm reopening this. That said, if anyone feels that trivial challenges insult their intelligence, I encourage them to seek out languages that make the task less trivial. \$\endgroup\$ – Martin Ender Jan 9 '17 at 9:19
  • 16
    \$\begingroup\$ Uo next: Subtract two numbers! \$\endgroup\$ – steenbergh Jan 9 '17 at 12:57
  • 7
    \$\begingroup\$ @wat Leaving no barrel-bottom unscraped, eh? \$\endgroup\$ – Gareth Jan 10 '17 at 12:39

124 Answers 124

1
\$\begingroup\$

Alice, 7 6 bytes

*/
o@i

Try it online!

Follows the same pattern as my solution for addition.

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

C, 56 bytes

main(int i,char**a){printf("%d",atoi(*++a)*atoi(*++a));}

compile

> gcc source.c

usage

> a 8 7

or

> ./a.out 8 7

explanation

main(int i,char**a) {  /* Begin program and accept command-line arguments.    */
   printf("%d",        /* First argument prints the (final) decimal result.   */
         atoi(*++a)    /* Returns int of program's 2nd command-line argument. */
         *             /* Multiplies the values of the 1st & 2nd arguments.   */
         atoi(*++a)    /* Returns int of program's 1st command-line argument. */
   );
}
\$\endgroup\$
  • \$\begingroup\$ Request: Don't put the byte count far away from the language and use a code block for the explanation. \$\endgroup\$ – CalculatorFeline Feb 22 '17 at 22:23
  • \$\begingroup\$ @CalculatorFeline Why? \$\endgroup\$ – veganaiZe Feb 22 '17 at 22:24
  • \$\begingroup\$ Well, I guess the byte count formatting is okay, but the explanation looks really weird. \$\endgroup\$ – CalculatorFeline Feb 22 '17 at 22:25
  • \$\begingroup\$ That's my style (for the moment)! If you don't like it then please offer me something more than really weird -- Thanks for the feedback. \$\endgroup\$ – veganaiZe Feb 22 '17 at 22:29
  • 2
    \$\begingroup\$ Your formatting is all over the place on my phone. Also, I'm sorry, but I just don't get why you'd include an explanation at all if you're not going to make it readable. \$\endgroup\$ – Dennis Feb 22 '17 at 23:07
1
\$\begingroup\$

Lean Mean Bean Machine, 12 bytes

OO
ii
 /
*
u
\$\endgroup\$
1
\$\begingroup\$

Whitespace, 4 bytes

	  

In some other languages, you could quote that as "\t \n". Expects two numbers on the stack and leaves the result on the stack.

As a complete program reading from standard input and writing to standard output, it would be 36 bytes:

   
 
 	
					   
 
 	
						  
	
 	

Try it online!

\$\endgroup\$
  • \$\begingroup\$ I know it's been quite a while, but you can golf 1 byte in the full program. Instead of Push_0, Duplicate, STDIN_as_integer, Retrieve for the second input, you can use Duplicate, Duplicate, STDIN_as_integer, Retrieve. Duplicate (SNS) is one byte shorter than Push_0 (SSSN). It will store the second input on the heap at the address of the first input (so if the first input is 3, it will store the second input (i.e. 5) in the heap at {3:5} instead of {0:5}). \$\endgroup\$ – Kevin Cruijssen Mar 13 '18 at 8:57
  • \$\begingroup\$ Ignore my comment above. Apparently you cannot use an negative integer as heap-address, so it would fail if the first STDIN is negative. \$\endgroup\$ – Kevin Cruijssen Mar 13 '18 at 10:31
  • \$\begingroup\$ @KevinCruijssen Interesting try, though. And I wouldn't be surprised if at least one existing Whitespace interpreter does allow negative heap addresses... \$\endgroup\$ – aschepler Mar 13 '18 at 13:04
1
\$\begingroup\$

Perl 5, 7 bytes

6 bytes of code + 1 for -p flag

$_*=<>

Try it online!

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

Lua, 32 bytes

i=io.read
print(i("*n")*i("*n"))

Try it online!

Program reads 2 numbers from STDIN and prints the result to STDOUT.


"But shouldn't you use io.write?"

Well according to the documentation,

[...] write uses the current output file, whereas print always uses the standard output. Finally, print automatically applies tostring to its arguments, so it can also show tables, functions, and nil.

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

Go, 84 bytes

package main
import."fmt"
func main(){a,b:=0,0;Scanf("%d%d",&a,&b);Printf("%d",a*b)}

Try it online!

Worth mentioning:

  • We import the fmt package to the global namespace by using import.. That way, we can refer to Scanf and Printf as global functions.

  • a and b are assigned to 0, as that is shorter than doing var a,b int.

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

Go, 28 bytes

func(a,b int)int{return a*b}

Try it online!

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

Ruby, 10 bytes

:*.to_proc

Try it online!

I really thought this might be shorter...

\$\endgroup\$
  • \$\begingroup\$ ->a,b{a*b} works too lol \$\endgroup\$ – dkudriavtsev Oct 7 '17 at 20:11
  • \$\begingroup\$ Yeah, I thought I'd try something different. :P \$\endgroup\$ – totallyhuman Oct 8 '17 at 3:09
1
\$\begingroup\$

C#, 27 bytes

delegate(a,b){return a*b;};
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! You can make this shorter with (a,b)=>a*b, or use currying to get a=>b=>a*b. However, someone has already posted this solution. \$\endgroup\$ – Pavel Nov 2 '17 at 1:57
1
\$\begingroup\$

Aceto, 6 bytes

riri*p

ri grabs input and converts to integer * multiplies them p prints it Try it online!

\$\endgroup\$
  • \$\begingroup\$ Also works in CJam, interestingly. \$\endgroup\$ – Esolanging Fruit Mar 11 '18 at 23:35
1
\$\begingroup\$

QBIC, 13 bytes

::[a|p=p+b}?p

Adapted my code from 'add two numbers'. This starts a loop and adds 'y' to itself 'x' times.

But seriously, a 6-byte solution is ::?a*b. : gets a cmd line parameter and class it 'a', the next : does the same for 'b', 'cause 'a' is already taken. * multiplies, and ? prints the result. This is virtually identical to this answer, only the operator is different.


Since some time now, QBIC can in-line the 'get var from cmd line'-command, and the above would be ?:*:, at 4 bytes.

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

Forked, 5 bytes

$$*%&

Try it online!

  • $$ - read two integers
  • * - multiply top two stack values
  • % - print top of stack as integer
  • & - "terminate", prevent IP from wrapping
\$\endgroup\$
1
\$\begingroup\$

Unnamed, 30 Bytes

This language was made after the question was asked, but I think this counts:

(Takes 2 inputs and prints the result of their multiplication)

, # >1 # , # >1 # _*.@0.@1 # .

Explanation

" # " is the command separator. Others will be explained here:

, #   / Take an input as integer, put it into the current pointer (initially 0)                      
    >1 # / Move the pointer 1 times to the right, now it's 1
         , # / Take another input as integer, put it into current pointer (now 1)
             >1 # / Move the pointer 1 times right, now it's 2
                  _*.@0.@1 # / assign the product of the value of pointer 0 and tha value
                              of the pointer 1 to the current pointer (2)
                             . / print out the value of the current pointer (2)
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG . \$\endgroup\$ – Muhammad Salman May 9 '18 at 5:56
1
\$\begingroup\$

Flobnar, 4 bytes

&
*@

Try it online!

\$\endgroup\$
  • \$\begingroup\$ :| this is too golfy \$\endgroup\$ – ASCII-only Aug 13 '18 at 7:38
1
\$\begingroup\$

Commodore BASIC v2 (C64, VIC-20 and some PET models), 27 tokenized BASIC bytes

This version uses the limited DEF FN keyword, See description here

 0 DEFFNA(B)=A*B:INPUTA,B:PRINTFNA(B)

Commodore BASIC v2, 14 tokenized BASIC bytes

 0 INPUTA,B:PRINTA*B

Both methods are likely compatible with all 8 BIT BASIC variants on Commodore home computers, but are not tested.

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

Bourne-shell-based langs all look pretty similar:

Zsh, 11 bytes

<<<$[$1*$2]

Bash, 13 bytes

echo $[$1*$2]

Dash/POSIX sh, 15 bytes

echo $(($1*$2))
\$\endgroup\$
  • \$\begingroup\$ $(( )) syntax also works for ksh93. The "fish" shell does its own thing, e.g. math "$1*$2" \$\endgroup\$ – roblogic Apr 1 '19 at 23:23
1
\$\begingroup\$

GFortran, 51 27 bytes

Fulfils the rules, I suppose integer overflow error is to be expected.

-24 thanks to Ørjan Johansen

Try It Online!

read(*,*)i,j
print*,i*j
end
\$\endgroup\$
  • 1
    \$\begingroup\$ Seems you have some redundant stuff. (Unlike ab, ij default to integer.) \$\endgroup\$ – Ørjan Johansen Mar 27 '19 at 17:26
  • \$\begingroup\$ Thanks! It's been about 20 years since I wrote any real Fortran :P \$\endgroup\$ – roblogic Mar 27 '19 at 23:37
1
\$\begingroup\$

3+ bytes in various methods of representing lambda calculus, taking numeral input as Church numerals.

19 Bytes, Untyped Lambda Calculus, using named arguments:

λx.λy.λz.x(y(z))

This is the most verbose version, . represents a lambda abstraction and parentheses represent an application

9 or 12 Bytes, Lambda Calculus, using De Brujin Indices:

λλλ3(2 1)

This uses De Brujin Indices instead of variable names, and function application is right-associative and implicit.

Replacing lambda symbols with backslashes (a pretty common form when Unicode is not available) yields us only 6 bytes

It's small, but we can go smaller. Using John Tromp's Binary Lambda Calculus representation, we get the binary representation 0000000111100111010, or separated into individual parts:

3 bytes, Untyped Lambda Calculus, using BLC representation

00 00 00 01 1110 01 110 10 xxxxx

Where the 5 xs are any padding bits.

Explanation

These implement the simple mult function for Church Numerals in the untyped lambda calculus.

In untyped lambda calculus, EVERYTHING is a function, including numbers. All these functions take a maximum of a single argument. So how do you represent arbitrary numbers? Church encodings!

In Church encoding, numbers are represented by repeated recursion. All numbers n are represented by a function taking an argument f, and returning a function taking an argument x, which returns f(x) called n times. For example:

0: lambda f: lambda x: x
1 = lambda f: lambda x: f(x)
2 = lambda f: lambda x: f(f(x))
3 = lambda f: lambda x: f(f(f(x)))

Etc etc.

All inputs and outputs in most lambda calculus systems are in the form of church numerals.

The multiplication function takes 3 arguments and returns the first argument called on the second called on the third:

mult = lambda m: lambda n: lambda x: m(n(x))

This in lambda calculus simply multiplies the numbers m and n together.

Calling mult(2)(3) using our previous definitions of 2 and 3 results in a function:

lambda f: lambda x: f(f(f(f(f(f(x))))))

Or 6, the result of our multiplication. All the "golfs" are really just more concise ways of representing untyped lambda calculus.

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

√ å ı ¥ ® Ï Ø ¿, 4 bytes

II*o

Almost identical to my answer for the Add two numbers question.

Explanation

I    › Take input from the command line, evaluate and push to stack
 I   › Take another input
  *  › Times the two values together and push to stack
   o › Output the first value on the stack
\$\endgroup\$
1
\$\begingroup\$

International Phonetic Esoteric Language, 4 bytes (WIP language)

ɪɪθo

No TIO interpreter yet, but is runnable by cloning the repository above, and calling python3 main.py "code here".

ɪɪθo
ɪ    ; push int
 ɪ   ; push int
  θ  ; pop, pop, push a * b
   o ; pop, print
\$\endgroup\$
1
\$\begingroup\$

Pepe, 19 bytes

rEeeREeerEEEEeEreEE

Try it online!

Input is a,b. Change the "Separated by" box into , to work.

Explanation:

rEeeREee            # take 2 inputs (not in the same stack)
        rEEEEeE     # A*B -> stack r
               reEE # output as number
\$\endgroup\$
  • \$\begingroup\$ Why is this non-competing? \$\endgroup\$ – pppery Oct 3 '19 at 3:27
  • \$\begingroup\$ @pppery Language postdates the challenge, but I'm removing it now. \$\endgroup\$ – u_ndefined Oct 4 '19 at 10:21
0
\$\begingroup\$

Groovy, 10 bytes

{x,y->x*y}

This is an unnamed closure.

Try it here!

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

Scala, 2 bytes

_*

This is a curried lambda / anonymous function. To use it, assign it to a variable:

val f:(Int=>Int=>Int)=_*
f(7)(9)                   //returns 63

How it works:

In Scala, the underscore can be used as a shorthand for the arguments.

_*_, for example, is syntactic sugar for (a,b)=>a*b.

Removing the second underscore is treating the method * of the first argument as a function, results in a curried function that multiplies its arguments.

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

Ruby, 10 bytes

->a,b{a*b}

Answer is two characters too short without this text apparently.

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

ForceLang, 36 bytes

def n io.readnum()
io.write n.mult n

Another fun use of def.

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

Rust, 14

I haven't seen Rust quiet often so let's use it.

|a:u8,b:u8|a*b

This is a lambda expression that takes to 8 bit ints and multiplies them.

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

Batch, 57 bytes

set "a1=%1" && set "a2=%2" && set x=%a1%*%a2% && echo %x%

&&: execute another command.

First command: Set %a1% as the first argument

Second command: Set %a2% as the second argument

Third command: Set %x% as %a1% * %a2%.

Fourth command: Type in the value of %x%.

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

SmileBASIC, 13 bytes

INPUT A,B?A*B

Input should be given as two numbers, separated by a comma.

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

Powershell, 17 Bytes

param($a,$b)$a*$b

takes 2 numbers, returns them multiplied out.

\$\endgroup\$

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.