Given a (floating-point/decimal) number, return its reciprocal, i.e. 1 divided by the number. The output must be a floating-point/decimal number, not just an integer.

Detailed specification

  • You must receive input in the form of a floating-point/decimal number...
    • ...which has at least 4 significant digits of precision (if needed).
    • More is better, but does not count in the score.
  • You must output, with any acceptable output method...
    • ...the reciprocal of the number.
    • This can be defined as 1/x, x⁻¹.
    • You must output with at least 4 significant digits of precision (if needed).

Input will be positive or negative, with absolute value in the range [0.0001, 9999] inclusive. You will never be given more than 4 digits past the decimal point, nor more than 4 starting from the first non-zero digit. Output needs to be accurate up to the 4th digit from the first non-zero one.

(Thanks @MartinEnder)

Here are some sample inputs:


Note that you will never be given inputs which have above 4 digits of precision.

Here is a sample function in Ruby:

def reciprocal(i)
    return 1.0 / i


  • All accepted forms of output are allowed
  • Standard loopholes banned
  • This is , shortest answer in bytes wins, but will not be selected.


  • You will never receive the input 0.


This challenge is obviously trivial in most languages, but it can offer a fun challenge in more esoteric and unusual languages, so some users are willing to award points for doing this in unusually difficult languages.

  • @DJMcMayhem will award a +150 points bounty to the shortest brain-flak answer, since brain-flak is notoriously difficult for floating-point numbers

  • @L3viathan will award a +150 points bounty to the shortest OIL answer. OIL has no native floating point type, nor does it have division.

  • @Riley will award a +100 points bounty to the shortest sed answer.

  • @EriktheOutgolfer will award a +100 points bounty to the shortest Sesos answer. Division in brainfuck derivatives such as Sesos is very difficult, let alone floating-point division.

  • I (@Mendeleev) will award a bounty of +100 points to the shortest Retina answer.

If there's a language you think would be fun to see an answer in, and you're willing to pay the rep, feel free to add your name into this list (sorted by bounty amount)


Here is a Stack Snippet to generate an overview of winners by language.

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 leaderboard snippet:

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

var QUESTION_ID=114544,OVERRIDE_USER=62393;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={};e.forEach(function(e){var o=e.language;/<a/.test(o)&&(o=jQuery(o).text().toLowerCase()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link,uniq:o}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.uniq>s.uniq?1:e.uniq<s.uniq?-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}#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=617d0685f6f3"> <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="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>

  • 23
    \$\begingroup\$ Please stop upvoting trivial answers \$\endgroup\$ – Kritixi Lithos Mar 30 '17 at 18:04
  • 15
    \$\begingroup\$ @KritixiLithos People can vote as they see fit. Given the simplicity of this challenge, most, if not all answers are something like 1/x. \$\endgroup\$ – NoOneIsHere Mar 30 '17 at 18:08
  • 9
    \$\begingroup\$ This isn't objectively specified without very clear detail on accuracy and precision. \$\endgroup\$ – Peter Taylor Mar 30 '17 at 18:10
  • 6
    \$\begingroup\$ What about accuracy? Presumably you want 4 sf of accuracy too, but then there's the issue of rounding. Floating point questions are hard to get right and very worth sandboxing. \$\endgroup\$ – Peter Taylor Mar 30 '17 at 20:27
  • 10
    \$\begingroup\$ -1, this is a poor challenge because using a builtin is the ONLY way to do it and know you have satisfied the "specification". If you have a standard floating point implementation, you can use it and tell yourself this is standard floating point, it must be ok. If you have to implement it yourself, there is no specification so you can't sensibly try to golf it. \$\endgroup\$ – feersum Mar 31 '17 at 5:12

90 Answers 90

1 2 3

NO!, 31 bytes

NB: Non-competing as language post-dates the challenge

NO! has 6 valid tokens: NOno!? and commands are made up of NO with the number of O determining the command.


More readable

NOOOOO?                 NOOOOO is the divide command and ? starts the arguments
       no!              no is 1 and ! separates the arguments            
          NOOOOOOOOOOO  This takes input from STDIN.

NOOOOOOOO?              This outputs the result of the       line
          no                                           first 

The equivalent pseudocode:

output divide 1, input

HODOR, 100 bytes

NB: Non-competing because why not? I'm never going to win with Hodor!

Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor,

If you must know how it works, I'll tell you.


Walder                                                                       Hodor hodor
Hodor?!                                                                     Hodor hodor hodor HODOR
Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor,        Hodor hodor hodor hodor hodor hodor
HODOR!!                                                                     Hodor hodor hodor hodor hodor
HODOR!!!                                                                    Hodor hodor (Hodor hodor hodor)


Walder - Start program


Hodor?! - Take input from STDIN


Hodor, Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor Hodor, Hodor, - Change accumulator value to it's reciprocal


HODOR!! - Output accumulator value as number


HODOR!!! - Kill Hodor (End the program)

  • \$\begingroup\$ "Wylis"? Someone didn't read the books. ;) \$\endgroup\$ – Martin Ender Apr 5 '17 at 12:09
  • \$\begingroup\$ @MartinEnder I read them but couldn't be bothered to look for his name in them. They are other 4000 pages long altogether. \$\endgroup\$ – caird coinheringaahing Apr 5 '17 at 12:11
  • \$\begingroup\$ awoiaf.westeros.org/index.php/Hodor :) \$\endgroup\$ – Martin Ender Apr 5 '17 at 12:11
  • \$\begingroup\$ @MartinEnder I can't believe I have defiled Hodor's memory like this! (Now I've got to go change all the answers!) \$\endgroup\$ – caird coinheringaahing Apr 5 '17 at 12:22

Pyth, 3 2 bytes

-1 byte thanks to Steven Hewitt


c is float division, with 1 and implicit input.

  • 1
    \$\begingroup\$ Pyth can fill in the Q implicitly, so c1 works just as well. \$\endgroup\$ – Steven H. Apr 8 '17 at 12:59

Keg, 1 byte

Try it online!

Keg, 3 bytes(SBCS)


TIO Divide 1 by friendly input

  • \$\begingroup\$ for 1 byte. \$\endgroup\$ – Lyxal Jan 20 at 22:02

Jellyfish, 3 bytes


Try it online!

Unary % computes the reciprocal. i is input, p is output.


Gol><>, 4 bytes


Online interpreter link


Dyvil, 5 Bytes

1 / _

Unfortunately we need the extra white space because /_ would be a single operator, and 1/ _ would parse differently


let f: double -> double = 1 / _
print(f(2)) // 0.5

Racket 7 bytes

(/ 1 x)

Full function:

(define (f x)
  (/ 1 x))


(f 1.56)



REXX, 12 bytes

say 1/arg(1)

Divides 1 by first argument. Precision is decided by NUMERIC DIGITS but defaults to at least 9 decimals.


JavaScript(ES7), 8 bytes



  • \$\begingroup\$ @fəˈnɛtɪk Oh dammit. Now I have to rollback to x**-1. \$\endgroup\$ – Matthew Roh Apr 5 '17 at 13:02
  • \$\begingroup\$ ** does not exist in ES6, it was added in ES7, which is why I specified your answer was ES7 \$\endgroup\$ – fəˈnɛtɪk Apr 5 '17 at 13:51
  • \$\begingroup\$ The Seventh Edition, also known as ECMAScript 2016, intended to continue the themes of language reform, code isolation, control of effects and library/tool enabling from ES2015, includes two new features: the exponentiation operator (**) and Array.prototype.includes. \$\endgroup\$ – fəˈnɛtɪk Apr 5 '17 at 14:01

Python 2.7, 17 25 bytes

Full program:


CGL (CGL Golfing Language), 6 bytes (non-competing)

This language postdates this challenge.



- decrements the current stack, so it is now -1, where input is placed

÷ Divides the first element of the stack by the second if it exists, otherwise (this case) it divides 1 by the first (reciprocal)

Output the last stack item (the result of ÷) and exit


Haskell, 4 bytes


Currying FTW!

  • \$\begingroup\$ alternatively (1/) \$\endgroup\$ – Zwei Apr 25 '17 at 23:32

Axiom, 57 bytes

f(x)==(y:=abs(x);y>9999 or y<0.0001=>"ObjFloatErr ";1./x)

test code and results

(21) -> [[i,f(i)] for i in [-2,-1,-0.0001,-0.00001,9999,10000]]
   [[- 2.0,- 0.5], [- 1.0,- 1.0], [- 0.0001,- 10000.0],
    [- 0.00001,"ObjError 1/x"], [9999.0,0.0001000100 0100010001],
    [10000.0,"ObjError 1/x"]]

Fourier (Non-Competing), 79 bytes


Try it online!

This is non-competing for two reasons:

  • Firstly, it does not fulfil the spec (it only works for inputs in the range -10 <= x <= 10
  • Secondly, it uses the functions L and P which were added after the writing of this challenge

So, this answer poses a challenge: can you complete this challenge in Fourier in the range -9999 <= x <= 9999? There are two bounties up for grabs:

  • 100 Rep Bounty for the first solution to complete this task without using the new functions L (log 10) and P (power)
  • 50 Rep Bounty for the shortest solution to complete this task using the new functions L (log 10) and P (power)

Note that on the Fourier github repo (https://github.com/beta-decay/Fourier/tree/master/fourIDE/editor) the FourIDE is up to date with L and P.

To-do list

  • Add explanation of code
  • \$\begingroup\$ For x=0 the 1/x=1/0 is not possible so the domain of function 1/x has to be [-a, -e] [e,a] for some 'a' big enough for them and 'e' little enough... \$\endgroup\$ – RosLuP Apr 17 '17 at 18:52

Convex, 1 byte


Try it online!


Jelly , 11 Bytes


This works without the built-in inverse function . (Who uses that anyway?).

Try it online!

How it works

   1,0      # Look at the list [1,0]
  ṭ         # Append (to the end)
²N          #  the negative of the square of the input
      Ær    # Find the roots to the polynomial with coefficients corresponding to the list as [greater root,lower root] pair
        Ḣ   # Head; get the first element of the roots (always positive)
         ×Ṡ # Multiply by the sign of the input (to accommodate negative input)

Batch, 69 67 + 39 (vbs section) = 106 bytes


@for /f "skip=1" %%n in ('cscript //nologo b.vbs 1/%1')do @echo %%n


  • call VBScript to calculate 1/argument
  • return the result


WScript.Echo Eval(WScript.Arguments(0))

Explanation:(my guess, I'm not good at VBS)

  • return the result calculated by Eval

Test cases

called from command line:

>a.bat 0.5134

>a.bat -0.5

Batch can't handle floating point division....

  • 1
    \$\begingroup\$ I can't test VBScript, but my feeling is, that if you change the VBS to WScript.Echo 1/WScript.Arguments(0), and change "1/%1" into ` "%1"`, you could save some bytes. \$\endgroup\$ – steenbergh Apr 18 '17 at 14:31

Perl 5, 7 bytes

The obvious subroutine.

  • \$\begingroup\$ I was under the impression that you could only omit the sub when passing it to a subroutine with a & prototype. \$\endgroup\$ – a spaghetto May 1 '17 at 18:39
  • \$\begingroup\$ @quartata, perldoc perlsub says: "The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code." \$\endgroup\$ – msh210 May 1 '17 at 19:54
  • \$\begingroup\$ Still, the result is not something that is callable as it stands. I would say it is invalid. \$\endgroup\$ – Ton Hospel Feb 1 '18 at 19:08

8087 machine code, 4 bytes

d9 e8   |   fld1
d8 f1   |   fdiv st0, st1

The obvious/trivial solution. Expects input in register st0.


Groovy, 9 bytes


Needs the .0g to denote big decimal notation on the 1, making the it unbox itself as a BigDecimal.

Input of 7.29349129124513204632593467635245678734521456789

Results in 0.13710854789123656486815482305643737234188188122

If you use an input of 214700000000000, however, without the .0g...

You get an error or nothing.


ARBLE, 3 bytes


Try it online!


Aceto 1.0, 4 3 bytes non-competing

Non-competing because the challenge predates Aceto. Assumes input number is on the stack, and leaves it on the stack.


1 pushes 1 on the stack, s swaps the top two values, and : does floating point division.

Also, this is the first Aceto answer!

edit: Saved 1 byte


Attache, 4 bytes


Try it online!

This is division (`/) left-bonded with 1, which is equivalent to reciprocal.


Bash, 15 bytes

dc -e"Fk$1_1^p"

Try it online!

dc               ::Use dc calculation
   -e            ::Evaluate argument as dc code
     "         " ::Quote
      Fk         ::F sig-figs (F is hex for 15)
        $1       ::$1 is initial value (the first argument)
           _1^   ::Raise $1 to power of -1
              p  ::Print result

KoopaScript, 48 bytes

def a i inp;setath o 1 / \%vuserInput;print \%vo

And how it works (KS isn't really golfable yet but it's fun nonetheless):

def a i                                          - define a function and call it a lot
        inp;                                     - pause execution until input
            setath o 1 / \%vuserInput;           - set 'o' to 1 / the input
                                      print \%vo - output 'o'

Try it online (paste the code into the left-hand box, press enter, then type a number, press enter, etc)

Now that KS has input, I can finally start using it for stuff that involves interaction :D (Tell me if this should be non-competing :P)


AWK, 10 7 bytes



awk '$0=1/$1' <<< "some number here"

or use the TIO link : Try it online!

Explanation: Replace the input line with its reciprocal. This is then evaluated and the entire line is printed if the evaluation in non-zero. Since the result can't be 0 we don't need to worry about not receiving output.


SenseTalk, 16 bytes

params r
put 1/r


params r # accept input
put 1/r  # get the reciprocal

W, 3 bytes

You know, we can't beat the built-ins.



a1S  % Stack : 1 a
   / % Divide.(1/a)
     % Output.

Rogex, 15 bytes


Try it online!

The actual language isn't on TIO yet, so a python 3.8 interpreter with the program in the code section and the python interpreter split in the header and footer is provided

Rogex is a newly developed language that I've recently discovered, so I though I'd give it a crack and write an answer.


701 300 # Set the buffer to 1 and place it in cell 0
001     # Get numeric input and place it into the buffer
600 200 # Divide cell 0 (1) by the buffer (input) and print

(╭☞´• ᗜ •`)╭☞ 100 answers! Woot! (⌐■◡■)

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.