21
\$\begingroup\$

Earlier, we did the pseudofactorial of a number, which is the LCM of the numbers from 1 to n.

It would be useful in adding fractions together.

However, we find that the denominator of 1/1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 is 20 instead of the pseudofactorial of 6, which is 60.

Your task is to find the denominator of 1/1 + 1/2 + ... + 1/n given positive integer n.

Testcases

 n result
 1 1
 2 2
 3 6
 4 12
 5 60
 6 20
 7 140
 8 280
 9 2520
10 2520
11 27720
12 27720
13 360360
14 360360
15 360360
16 720720
17 12252240
18 4084080
19 77597520
20 15519504
21 5173168
22 5173168
23 118982864
24 356948592
25 8923714800
26 8923714800
27 80313433200
28 80313433200
29 2329089562800
30 2329089562800

References

Leaderboard

var QUESTION_ID=82815,OVERRIDE_USER=48934;function answersUrl(e){return"http://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"http://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>

Okx
16.5k5 gold badges45 silver badges114 bronze badges
asked Jun 13, 2016 at 17:23
\$\endgroup\$
2
  • \$\begingroup\$ How big of an input does it have to work for? \$\endgroup\$ Commented Jun 13, 2016 at 21:12
  • \$\begingroup\$ @BradGilbertb2gills As big as is reasonable. \$\endgroup\$ Commented Jun 13, 2016 at 22:24

26 Answers 26

8
\$\begingroup\$

M, (削除) 9 (削除ここまで) 6 bytes

Thanks to FryAmTheEggman for saving 3 bytes! Code:

RİSg1İ

M has a huge advantage here, because it works with fractions rather than floats. Explanation:

R # Get the list [1 ... n].
 İ # Inverse each, resulting into [1/1, 1/2, 1/3, ..., 1/n].
 S # Sum it up. (86021/27720 for n=12)
 g1 # Compute the greatest common denominator with n. (1/27720 for n=12)
 İ # Calculate the inverse again. (27720 for n=12)

Uses the Jelly encoding. Try it online!.


Also, there is a 4-byte solution, which outputs a leading zero sometimes (e.g. 280 -> 0280). I'm not sure if this is allowed or not:

RİSV

Try it online!.

answered Jun 13, 2016 at 18:20
\$\endgroup\$
4
  • 1
    \$\begingroup\$ 1. The explanation of the 6-byte code isn't quite correct. computes the gratest common divisor of the fraction and n. Using g1 would probably be clearer. 2. V casts the fraction to a string and evaulates it niladically. <num>/ is (non-cumulative) reduce by a niladic operator. This is nonsense, but since there's only one number (the implicit argument 0), it simply does nothing. The next link, the denominator, is niladic, so the previous return value is printed implicitly and replaced with that nilad. \$\endgroup\$ Commented Jun 13, 2016 at 19:49
  • \$\begingroup\$ @Dennis Thanks! Fixed the explanation. \$\endgroup\$ Commented Jun 13, 2016 at 20:13
  • \$\begingroup\$ @Adnan Is there any documentation for M? \$\endgroup\$ Commented May 30, 2017 at 7:12
  • \$\begingroup\$ @Challenger5 Not that I know of. It is actually a variant of Jelly, but with arbitrary precision fractions. The Jelly documentation can be used, but be awate that a lot of features implemented in Jelly aren't implemented in M. \$\endgroup\$ Commented May 30, 2017 at 7:33
6
+600
\$\begingroup\$

Ruby, (削除) 57 (削除ここまで) 47 bytes

->n{(1..n).reduce{|a,i|a+1.to_r/i}.denominator}

Thanks to Kevin Lau for shortening this by ten bytes.

answered Jun 14, 2016 at 0:26
\$\endgroup\$
2
  • \$\begingroup\$ Assign a variable to 1.to_r so you don't need to do string injection and conversion. Also, since Ruby's default for reduce is to use the first element as the initial, and 1/1=1, you don't need to specifically set 0 as the initial value. \$\endgroup\$ Commented Jun 14, 2016 at 5:43
  • \$\begingroup\$ In modern Ruby 1.to_r can be 1r \$\endgroup\$ Commented Jan 17, 2022 at 13:58
5
\$\begingroup\$

Julia, 22 bytes

An anonymous function.

n->1.//(1:n)|>sum|>den
answered Jun 13, 2016 at 18:00
\$\endgroup\$
1
  • \$\begingroup\$ Same length: n->sum(inv,1//1:n).den \$\endgroup\$ Commented Jun 14, 2016 at 0:29
4
\$\begingroup\$

Mathematica, 27 bytes

An anonymous function.

Denominator@*HarmonicNumber

For example:

 In[1] := (Denominator@*HarmonicNumber)[10]
 Out[1] = 2520
answered Jun 13, 2016 at 17:57
\$\endgroup\$
3
  • \$\begingroup\$ You could find a 26-byte solution if you dig into the chat :) \$\endgroup\$ Commented Jun 13, 2016 at 17:57
  • \$\begingroup\$ Oh! I should let Martin post that one, if he likes. This one is adorably literal, so I’ll keep it. \$\endgroup\$ Commented Jun 13, 2016 at 18:01
  • \$\begingroup\$ Would you exemplify how the code is used? \$\endgroup\$ Commented Jun 13, 2016 at 20:15
4
\$\begingroup\$

Python 2, (削除) 69 (削除ここまで) 67 bytes

a=b=k=r=1
exec'a=a*k+b;b*=k;k+=1;'*input()
while r*a%b:r+=1
print r

Test it on Ideone.

How it works

Let H(n) be the sum of the multiplicative inverses of the first n positive integers. At all times, we have that a / b = 1 + H(k - 1). In fact, a, b, and k are all initialized to 1, and 1 / 1 = 1 = 1 + H(0).

We repeat the code snippet

a=a*k+b;b*=k;k+=1;

(as a string) n (input) times and execute the result. In each step, we update a, b, and k using the identity a / b + 1 / k = ak / bk + b / bk = (ak + b) / bk.

After all copies have been executed, a / b = 1 + H(n), which has the same denominator as H(n).

The fully reduced form of a / b is (a ÷ gcd(a,b)) / (b ÷ gcd(a,b)). Instead of calculating the greatest common divisor, we initialize r as 1 and keep incrementing r until ra is a multiple of b.

Clearly, this makes ra the least common multiple of a and b. Since gcd(a,b) · lcm(a,b) = ab, we have that b ÷ gcd(a,b) = lcm(a,b) ÷ a = ra ÷ a = r, making r the desired output.

answered Jun 14, 2016 at 4:36
\$\endgroup\$
0
3
\$\begingroup\$

Haskell, 52

Import Data.Ratio
f n=denominator$sum[1%k|k<-[1..n]]

If the file is loaded into GHCI, f can be used as a function.

answered Jun 15, 2016 at 0:24
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Presumbably you mean import lowercase? It saves a byte to use a map instead of a comprehension: sum$map(1%)[1..n] \$\endgroup\$ Commented Jun 15, 2016 at 5:47
2
\$\begingroup\$

Jelly, 9 bytes

!©÷RSg®®÷

Try it here.

 Argument: n
! ÷R Compute [n!÷1, n!÷2, ... n!÷n].
 © (And store n! in the register.)
 S Find the sum of this list.
 g® GCD with n!.
 ®÷ Divide n! by this GCD.
answered Jun 13, 2016 at 18:06
\$\endgroup\$
1
  • \$\begingroup\$ I believe it is possible to achieve the same bytecount without that register. \$\endgroup\$ Commented Jun 13, 2016 at 22:49
2
\$\begingroup\$

MATL, (削除) 14 (削除ここまで) 13 bytes

:p:G:!/s1\&X<

Try it online!

Explanation

For input N, the output is upper-bounded by N! (factorial of N). The code computes n/k for n = 1, ..., N! and for k = 1, ..., N. Then it sums over k, which gives the harmonic number multiplied by each n. The desired result is the index n of the first of those values that is an integer.

answered Jun 13, 2016 at 17:52
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 8 bytes

Code:

!Ð1L/O¿/

Explanation:

! # Take the factorial of the input.
 Ð # Triplicate this.
 1L # Get the list [1 ... input].
 /O # Divide and sum up.
 ¿ # Get the GCD of the sum and the factorial.
 / # Divide the factorial by this.

There might be some accuracy problems for n > 19 due to Python's division... Uses the CP-1252 encoding.

Try it online!.

answered Jun 13, 2016 at 18:26
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 26 bytes

Denominator@Tr[1/Range@#]&

An unnamed function taking n as input and returning the denominator. Uses the standard trick of abusing Tr (trace) to sum the list of reciprocals.

answered Jun 15, 2016 at 7:35
\$\endgroup\$
2
\$\begingroup\$

Husk, 6 bytes

is\ṁ\ḣ

Try it online!

Not too hard in Husk since it can do math with rational numbers. The hard part was extracting the denominator, I ended up inverting the fraction, converting it to string, and getting the first number from that string.

Explanation

is\ṁ\ḣ
 ḣ range [1..n]
 ṁ sum the result of this function for each number:
 \ inverse
 \ invert
 s convert to string
i get the first number in the string (the numerator)
answered Feb 18, 2021 at 6:38
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 88 bytes

m=>{for(d=1,i=0;i<m;d*=++i);for(n=i=0;i<m;n+=d/++i);for(g=d;g;[g,n]=[n%g,g]);return d/n}

Only works up to m=20 because of the limits of JavaScript's numeric precision.

answered Jun 13, 2016 at 18:29
\$\endgroup\$
1
\$\begingroup\$

Pari/GP, 30 bytes

n->denominator(sum(i=1,n,1/i))

Try it online!

answered May 30, 2017 at 6:59
\$\endgroup\$
1
\$\begingroup\$

Stax, 5 bytes

┬ΓΣ╞]

Run and debug it

6 bytes without packing.

answered Feb 18, 2021 at 6:35
\$\endgroup\$
1
\$\begingroup\$

Whispers v3, 79 bytes

> Input
>> 1!
>> 2∕R
>> (1]
>> Each 3 4
>> ∑5
>> 6⊓2
>> 2∕7
>> Output 8

Try it online!

Same idea as Lynn's Jelly answer.

answered Feb 18, 2021 at 6:49
\$\endgroup\$
1
\$\begingroup\$

Thunno, \$ 12 \log_{256}(96) \approx \$ 10 bytes

(Actually 9.88 bytes but that doesn't show up on the leaderboard)

Fztz!R+/SAG/

Attempt This Online!

Port of Adnan's 05AB1E answer.

Explanation

Fztz!R+/SAG/ # Implicit input
Fzt # Get factorial and triplicate
 z!R+ # Push range(1, input+1)
 /S # Divide and sum
 AG/ # Get GCD and divide
answered Feb 25, 2023 at 14:50
\$\endgroup\$
0
\$\begingroup\$

J, 20 bytes

(!%!+.[:+/!%1+i.)@x:

Based on the approach used by @Lynn's solution.

If precision is not necessary for large values of n or if we can assume n will be passed as an extended integer, suffixed by x, a shorter solution can be used for 15 bytes.

!%!+.[:+/!%1+i.

Usage

 f =: (!%!+.[:+/!%1+i.)@x:
 f 30
2329089562800
 (,:f"0) >: i. 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 6 12 60 20 140 280 2520 2520 27720 27720 360360 360360 360360

Explanation

(!%!+.[:+/!%1+i.)@x: Input: n
 x: Convert n into an extended integer
 i. Creates the range [0, 1, ..., n-1]
 1+ Add one to each, range is now [1, 2, ..., n]
 ! Get factorial of n
 % Divide n! by each value in the range [1, 2, ..., n]
 [:+/ Sum those values
 ! Get n!
 +. Get gcd between n! and the sum
 ! Get n!
 % Divide n! by the gcd and return
answered Jun 13, 2016 at 21:31
\$\endgroup\$
0
\$\begingroup\$

Perl 6, (削除) 36 (削除ここまで) 32 bytes

(削除) {([+] 1.FatRat X/1..$_).denominator} (削除ここまで)
{([+] 1.FatRat X/1..$_).nude[1]}

Explanation:

{
 (
 [+] # reduce with &infix:<+>
 # the following produces a Seq of Rational numbers
 # 1/1, 1/2, 1/3 ... 1/n
 1.FatRat # FatRat.new: 1,1
 X/ # crossed using &infix:</>
 1 .. $_ # Range from 1 to the input inclusive
 ) # resulting in a FatRat
 .nude # (nu)merator (de)nominator
 .[1] # grab the denominator
}

Test:

my &hd = {([+] 1.FatRat X/1..$_).nude[1]}
say (1..10)».&hd; # (1 2 6 12 60 20 140 280 2520 2520)
say hd 100; # 2788815009188499086581352357412492142272
say chars hd 1000; # 433
say chars hd 10000; # 4345
answered Jun 13, 2016 at 21:56
\$\endgroup\$
0
\$\begingroup\$

Hoon, 95 bytes

|=
@
=+
n=(gulf 1 +<)
=+
f=(roll n mul)
(div f d:(egcd f (roll (turn n |=(@ (div f +<))) add)))

Create list [1...n], fold over it with ++mul for the factorial, create list [n!/1, n!/2, ... n!/n] and sum it, find GCD of n! and the list, and divide the factorial by that number.

There's probably a much easier way to calculate the denominator, but I can't figure it out :/

answered Jun 14, 2016 at 22:34
\$\endgroup\$
2
  • \$\begingroup\$ Oh Hoon, why your tokenizer needs so many redundant whitespaces? \$\endgroup\$ Commented Jun 14, 2016 at 22:54
  • \$\begingroup\$ All my Hoon entries look ugly because of the newlines :( Normal Hoon code uses two spaces between tokens, but one newline is shorter \$\endgroup\$ Commented Jun 14, 2016 at 23:40
0
\$\begingroup\$

Python 3, (削除) 153 150 146 (削除ここまで) 142 bytes

I'm sure this can golfed further. But I'm new here

f=lambda x:0**x or x*f(x-1)
z=int(input());i=f(z)
r=sum(i/y for y in range(1,z+1)) 
p=lambda a,b:a if b<1else not a%b+b or p(b,a%b)
print(i/p(r,i))
answered Jun 13, 2016 at 19:17
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Commented Jun 13, 2016 at 22:30
0
\$\begingroup\$

Axiom, 34 bytes

f(x)==denominator(sum(1/n,n=1..x))

test

(24) -> [[i,f(i)] for i in 1..30]
 (24)
 [[1,1], [2,2], [3,6], [4,12], [5,60], [6,20], [7,140], [8,280], [9,2520],
 [10,2520], [11,27720], [12,27720], [13,360360], [14,360360], [15,360360],
 [16,720720], [17,12252240], [18,4084080], [19,77597520], [20,15519504],
 [21,5173168], [22,5173168], [23,118982864], [24,356948592],
 [25,8923714800], [26,8923714800], [27,80313433200], [28,80313433200],
 [29,2329089562800], [30,2329089562800]]
 Type: List List Expression Integer
answered May 30, 2017 at 10:19
\$\endgroup\$
0
\$\begingroup\$

PHP, 81 Bytes

for($p=1;$z++<$argn;$n=$n*$z+$p/$z)$p*=$z;for($t=1+$n;$p%--$t||$n%$t;);echo$p/$t;

Try it online!

answered May 30, 2017 at 11:19
\$\endgroup\$
0
\$\begingroup\$

Japt, 12 bytes

l
/yNÎõ@/XÃx

Try it

l\n/yNÎõ@/XÃx :Implicit input of integer U
l :Factorial
 \n :Reassign to U
 / :Divide by
 y :GCD with
 N : Array of all inputs
 Î : First element (i.e., original input)
 õ : Range [1,NÎ]
 @ : Map each X
 /X : Divide U by X
 Ã : End map
 x : Reduce by addition
answered Oct 24, 2022 at 14:38
\$\endgroup\$
0
\$\begingroup\$

Factor + math.unicode, 35 bytes

[ 1 swap [1,b] n/v Σ denominator ]

Try it online!

answered Oct 27, 2022 at 1:38
\$\endgroup\$
0
\$\begingroup\$

Arturo, 38 bytes

$=>[denominator∑map..1&=>reciprocal]

Try it

answered Feb 25, 2023 at 16:04
\$\endgroup\$
0
\$\begingroup\$

J-uby, 28 bytes

:+|:sum+(:/&1r)|:denominator

Attempt This Online!

answered May 2 at 17:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.