# What is the moment of inertia of a Gosper island?

We know that regular hexagons can tile the plane but not in a self-similar fashion. However we can construct a fractal known as a Gosper island, that has the same area as the hexagon but has the property that when surrounded by 6 identical copies produces a similar shape, but with dimensions scaled by a factor of $\sqrt{7}$.

What is the distance between two of the centers? Is it the same as the distance between hexagons of the same area? ie. If I start with a hexagon of area A, then construct a Gosper island and place it next to an identical copy, would the distance still be the same as if they were hexagons? Or does the scaling factor come into play somewhere? Right now I think the answer is $\sqrt{3}/2$, as for the hexagon.

The reason I ask is that I'm trying to calculate the Gosper island's moment of inertia through an axis through its centre of mass and perpendicular to the plane of the island.

If we assume that the moment of inertia is always proportional to the mass, and proportional to the square of a characteristic length scale, then $$I = \gamma Ml^2,$$ where $\gamma$ is a constant, $l$ is the 'diameter' of the island, in a hexagon this would be the distance between two opposite vertices. Shrink the Gosper island by the scaling factor and surround it by six others. This self-similarity technique is super cute, and can be used to calculate the moment of inertia of an equilateral triangle, and can be extended to a square/rectangle quite easily. Fractals, having a high degree of self-similarity, seem amenable to this technique - here I calculate the moment of inertia for a Koch snowflake.

$\hspace{1.3cm}$

Using the principle of superposition, $$I = I_{\text{centre}} + 6I_{\text{edge}},$$ where $$I_{\text{centre}} =\gamma \frac{M}{7}\left(\frac{l}{\sqrt{7}}\right)^2 = \gamma \frac{Ml^2}{49} = \frac{I}{49}.$$

Now, by the parallel axis theorem $\displaystyle I_{\text{edge}} = I_{\text{COM}} + Md^2$ where $$\displaystyle I_{\text{COM}} = \frac{I}{49}$$ and $\displaystyle d= \frac{\sqrt{3} l}{2}$ (this was one source of error), so $\displaystyle I_{\text{edge}} = \frac{I}{49} + \frac{3Ml^2}{4},$ and \begin{align*} I &= \frac{I}{49} + 6\left(\frac{I}{49}+ \frac{3Ml^2}{4}\right), \\ I & = \frac{I}{7} + \frac{9Ml^2}{2}, \\ \frac{6I}{7} & = \frac{9Ml^2}{2}, \\ I & = \frac{21Ml^2}{4}. \end{align*}

This seems incorrect? It feels wrong, comparing to a disk of radius $l/2$ which has moment of inertia $Ml^2/4$ it seems far too large.

It would also be nice if we could verify our answer numerically or otherwise. Any references are also appreciated.

• The center of mass of the Gosper island is indeed the same as the center of the initial hexagon. This, as well as the moment of inertia can be computed using the technique of self-similar integration as in my answer to this question. I could provide a few more details but I get the feeling this might be an exercise? – Mark McClure May 17 '16 at 13:18
• Nope, just something I thought up after teaching the self-similarity method for finding the MOI of a triangle/square. Thankyou so much for the link! I suppose this can be done for an fractal with enough rotational symmetry to tile the plane? Please provide as many details as you wish, in an answer if you like. – Bennett Gardiner May 18 '16 at 2:05
• By the way, the polar inertia of a disk is not $ml^2/4$ (That is the x or y inertia) but $Ml^2/2$. – Urukann May 20 '16 at 4:40
• Isn't that only if $l$ is the radius though? In my formulation I was trying to use the diagonal of the hexagon, so it made more sense to compare to a disk with $l$ as the diameter. – Bennett Gardiner May 20 '16 at 6:19
• @BennettGardiner: IMO this is a source of confusion (especially if you don't explain it). The standard formula is $I=MR^2$ where $R$ is an equivalent radius (AKA gyration). I found it more effective to work with unit area shapes, so that the mass can be simplified, and $R$ conveys all shape information. – Yves Daoust May 20 '16 at 14:40

I think that your $\frac{\sqrt{3}}{2}$ for the distance between hexagons center is not right... The distance from an hexagon center to an edge is $\frac{r\sqrt{3}}{2}$, thus the distance between two hexagons of radius $\frac{l}{2\sqrt{7}}$ that touch by an edge should be: $$d = l\sqrt{\frac{3}{28}}$$

Now, if we take back your computation: $I = \frac{I}{49} + 6 \left(\frac{I}{49} + \frac{3Ml^2}{28}\right)$

This gives us : $I = \frac{3}{4} M l^2$, which may still not be the right answer.

It would be nice to compare this value to numerical methods, I'll look into it.

e/ I ran some numerical simulation, unfortunately it does not seem to confirm the above result.

How I did it:

• Starting from the code linked in this page, I generated the all points composing the outer shape of the gosper island.
• Then, I trimmed the generating points to remove duplicates
• I approximate the Gosper island as being star-shaped (This is not perfectly true, at least for $n=5$). Then its inertia is the sum of the inertia of the triangles composed of the origin and two consecutive points. Note that to get the actual inertia, one has to divide by the shape's area (Because when evaluating the triangle's inertia, we consider it has a surfacic mass of 1.). All triangle related formulas are available on Wolfram Alpha.

The results show that indeed the inertia is proportional to $l^2$, but its ratio to the value conjectured above is not 1, but a constant close to $\frac{4}{7}$: $$I_{gosper} \approx 0.568582263418 \frac{3}{4} M l^2$$

Unfortunately, it seems that this error is not related to the star-shaped approximation: I ran another experiment, this time using the Seidel program from the University of North Carolina at Chapel Hill. It allowed me to find a triangulation of the inner area of the Gosper island. Using another (similar) code I could check that the computation for a radius of 1. does yield the same ration between expected inertia (0.75) and the actual inertia (0.42856647032), with a similar ratio of 0.571421960426. Note that this inertia is very close to $\frac{3}{7}$, (best fractional approximation with a denominator inferior to fifteen thousand).

Actually, I had forgotten that the characteristic dimension is not the diameter, but the radius, thus the ratio is 0.142855490107, very close to $\frac{1}{7}$.

Using this method for a Koch snowflake yields pretty correct results: for a snowflake of radius $r \approx 1.44$ (I forgot to scale the step size properly) I get an inertia of $I_{koch} \approx 0.736036125705$ while the one given by $Ml^2/11 \approx 0.7435999999999999$

e/ I found the error: The mass of a "small" Gosper island is not $M$, but $\frac{M}{7}$, thus the missing factor 7. This is due to the fact that we make the assumption of a uniform density Gosper Island, thus its mass is proportional to its area.

We can rewrite our original equation: $$I_{edge} = I_{center} + \frac{M}{7}d^2\\ d = l \sqrt{\frac{3}{28}}$$

Which gives us: $$I = \frac{I}{49} + 6 \left( \frac{I}{49} + \frac{3Ml^2}{7\cdot 28}\right)$$

And finally:

$$I = \frac{3Ml^2}{28}$$

• Bah, forgot to scale the distance $d$. Thanks, this sounds much more reasonable. If you could confirm using numerical methods with some explanation of how you did it, it would put it to rest and I'd definitely accept/award the bounty. – Bennett Gardiner May 19 '16 at 12:42
• I just added some numerical simulation. However, it does not confirm my above conjecture. It may be because my code is quite dirty, but it may also be an error in the reasoning... Cheers – Urukann May 20 '16 at 4:37
• Interesting, thanks for your efforts, looks like we still have some way to go. Can you use the code to check the Koch snowflake case I linked? It code provide a check on the code For the snowflake, $I = Ml^2/11$ where $l$ is the largest 'diameter' of the snowflake (tip to tip) I really felt like this method should work, I wonder where the error lies! – Bennett Gardiner May 20 '16 at 6:22
• Hum, I checked with the Koch snowflake (my code was easier to modify than expected !): I get "correct" results. I noticed that I forgot to use the diameter instead of the radius, so we are off by another factor 4 I'm guessing... – Urukann May 20 '16 at 6:44
• Sorry, this is getting confusing, but no: I calculated the MOI for a radius 1 Gosper Island to be 0.42856647032, that is to say, $I = \frac{3Mr^2}{7} = \frac{3Md^2}{7 \cdot 4}$, meaning that we are missing a factor $\frac{1}{7}$. – Urukann May 20 '16 at 6:58

Yes, the distance between those hexagon-like shapes in a hexagonal lattice is the same as the distance between centres of hexagons of the same area in a hexagonal lattice.

The reason is that "in the long run" the area per mesh must be the same. That is, a sufficiently large circular disk contains both Gosper islands and hexagons in a number approximately equal to area of the disk dividied by area of the shape (with an error in the order of magnitude proportional to the cirumference of the disk).

The area inside the hexagon is made of one whole island and exactly six thirds, by symmetry.

Hence for an island of unit area, the distance between centers is such that

$$3\frac{\sqrt3}2d^2=3,$$

$$d=\sqrt{\frac2{\sqrt3}}.$$

To compute the moment of inertia, we will work with the radius of gyration and for an island of unit area.

$$I=MR^2$$ where $M$ is the mass.

For the assembly in the figure, enlarging by the factor $\sqrt7$ and using the axis theorem,

$$7M7R^2=49I=I+6(I+Md^2),$$

giving

$$R=\frac d{\sqrt7}=\sqrt{\frac{2}{7\sqrt3}}=0.406149258\cdots$$

This compares to the radius of gyration of a unit area disk,

$$R'=\frac1{\sqrt{2\pi}}=0.398942280\cdots$$

and that of a unit area hexagon,

$$R''=\sqrt{\frac{10}{36\sqrt3}}=0.400468569\cdots$$

• Interesting, so to scale this to an island with diameter $l$, would we simply scale this distance by $l$? – Bennett Gardiner May 20 '16 at 6:57
• Or $\sqrt{3/28}l$, like in the other poster's answer? I'm afraid I've confused myself quite a bit with the length scales. – Bennett Gardiner May 20 '16 at 7:00
• @BennettGardiner: I have no idea of the value of the diameter $l$, but you don't need it for the computation of the moment. – Yves Daoust May 20 '16 at 7:03
• I'm still trying to figure out your distance $d$. If that is the radius of gyration, what would the moment of inertia be? – Bennett Gardiner May 20 '16 at 7:32
• My confusion is part of why I asked the question. I am inclined to believe your answer more now that you have posted a comparison with the hexagon of unit area, in my mind they should have been very similar. – Bennett Gardiner May 20 '16 at 14:18


# Number of strings, when each character must occur even times

I was reading this question on programmers.StackExchange and wanted to try a combinatorics approach to solve the following problem:

Let $S=\{A,B,C,D\}$ be a set of characters and $n$ a positive natural, find the number of strings of length $n$ composed of characters in $S$ such that each character occur even times.

I tried to solve it by myself but I am stuck and I would appreciate a hint to solve this kind of problems. Also, there are similar questions on this site for not quite exactly the same problem, but I didn't find an answer that could help me.

## Current attempt

First, when $n$ is odd, the result must be zero. A string satisfying the desired property would necessarly have an even length, as a permutation of the concatenation of substrings of even lengths (each substring being a character from $S$ repeatead even times).

Now, let's suppose that $n$ is even.

If we have a mapping $c$ from $S$ to $\mathbb{N}$ assigning the number of occurence of each character (e.g. $c_A=0, c_B=2, c_C=4, c_D=0$), then the number of strings $N(c)$ we can produce with this mapping would be a k-permutation of characters, as we choose a string of size $n$ with $c_A$ times $A$, $c_B$ times $B$, etc. :

$$N(c) = \frac{n!}{c_A! c_B! c_C! c_D!}$$

Also, I can evaluate the number of such mappings $c$: this is equivalent to finding the number of strings where characters appear in order with varying occurences. For example, with $n=4$:

$$\begin{array}{c|cccc} & c_A & c_B & c_C &c_D \\ \hline AAAA & 4 & 0 & 0 & 0 \\ AABB & 2 & 2 & 0 & 0 \\ AACC & 2 & 0 & 2 & 0 \\ \dots\\ \end{array}$$

The number of strings of size $n$ with an even number of each character is exactly the same as the number of strings of size $k=n/2$ with single characters (just imagine that AA, BB, CC, DD are characters). So, the number of mappings is the number of combinations of characters from $S$, with repetition, like the following ones with $k=2$:

AA AB AC AD
BB BC BD
CC CD
DD

That is given as a $k$-combination of 4 elements:

$$N_{mapping}(k) = \binom{|S|+k-1}{k} = \binom {3+k}{k}$$

This is where I'am stuck. I wanted to combine this number of mappings with the number of permutations computed by each mapping, previously, but I can't ($N(c)$ depends on actual values of the mapping $c$). Also, I am sure there is a more straightforward approach, but I don't know how to proceed. Thanks for any help you could provide.

• I might miss something, but polynomial coefficient seems to work: $\binom{n}{2k} \cdot \binom{n-2k}{2j} \cdot \binom{n-2k -2j}{2m}$ – Alex Feb 13 '15 at 13:26
• @Alex In your formula, do $k$ $j$ and $m$ stand for half the number of occurences of each character? I understand it as: choose first $2k$ elements from $n$, then $2j$ from $n-2k$, and so on...? Are $k$, $j$ and $m$ supposed to be known? Sorry, I have very little experience with this. – coredump Feb 13 '15 at 13:39
• Yes, but it seems like not every $\binom{2n}{2k}$ is even, e.g. $\binom{6}{4}$ – Alex Feb 13 '15 at 14:56

Generating functions can be applied to this problem. However, since the order of letters in a string is important, exponential generating functions are appropriate (not ordinary ones). So, suppose the alphabet $S$ has $m$ letters and let $a_n$ be the number of strings of length $n$ over the alphabet $S$ with an even number of each letter. Let $g(x)=\sum_{n\ge0}\frac{a_n}{n!}x^n$ be the exponential generating function of $\langle a_n:n\ge0\rangle$. Then, $$g(x)=\left(\sum_{n\textrm{ even}}\frac{x^n}{n!}\right)^m=\left(\frac{e^x+e^{-x}}2\right)^m.$$

In the case of $m=4$, $g(x)=\frac1{16}(e^{4x}+4e^{2x}+6+4e^{-2x}+e^{-4x})$. Then, $a_n=\left[\frac{x^n}{n!}\right]g(x)$ and if $n$ is even, $a_n=\frac{n!}{16}\left(\frac{2\cdot4^n}{n!}+\frac{8\cdot2^n}{n!}\right)=\frac18(4^n+4\cdot2^n)$. In particular, $a_4=40$.

Note: based on the form of the solution of $a_n$, I suspect there's a direct combinatorial argument (but I don't know it).

• I am very impressed. I should have a look at generating functions. Thanks a lot, I'll study this and try to understand what it all means. – coredump Feb 13 '15 at 21:04
• @coredump: If you want to take a look at generating functions, one excellent place to start is Herb Wilf's free book: math.upenn.edu/~wilf/gfologyLinked2.pdf. After reading his book, I was hooked. – Rus May Feb 13 '15 at 23:41

Let $m=|S|$ be the number of distinct characters, and let $a_n$ be the number of strings in $S^n$ having an even number of each character in $S$. Let

$$g(x)=\sum_{n\ge 0}\frac{a_n}{n!}x^n$$

be the exponential generating function (egf) for $\langle a_n:n\in\Bbb N\rangle$. (The egf is wanted because the order of the characters matters.) The egf for the sequence given by $$a_n=\begin{cases}0,&\text{if }n\text{ is odd}\\1,&\text{if }n\text{ is even}\end{cases}$$ is

$$\sum_{n\ge 0}\frac1{(2n)!}x^{2n}=\frac12(e^x+e^{-x})\;,$$

so

$$g(x)=\left(\sum_{n\ge 0}\frac1{(2n)!}x^{2n}\right)^m=\frac1{2^m}(e^x+e^{-x})^m\;.$$

Now

\begin{align*} (e^x+e^{-x})^m&=\sum_{k=0}^m\binom{m}ke^{kx}e^{-(m-k)x}\\\\ &=\sum_{k=0}^m\binom{m}ke^{(2k-m)x}\\\\ &=\sum_{k=0}^m\binom{m}k\sum_{n\ge 0}\frac{(2k-m)^n}{n!}x^n\\\\ &=\sum_{n\ge 0}\frac1{n!}\left(\sum_{k=0}^m\binom{m}k(2k-m)^n\right)x^n\;, \end{align*}

so

$$a_n=\frac1{2^m}\sum_{k=0}^m\binom{m}k(2k-m)^n\;.\tag{1}$$

Note that $2(m-k)-m=m-2k=-(2k-m)$, so $(1)$ is indeed $0$ when $n$ is odd. When $n$ is even and positive we can rewrite $(1)$ as

$$a_n=\frac1{2^{m-1}}\sum_{k=0}^{\lfloor m/2\rfloor}\binom{m}k(m-2k)^n\;.$$

For instance, if $m=4$, then

\begin{align*} a_{2n}&=\frac18\left(\binom40(4-0)^{2n}+\binom41(4-2)^{2n}+\binom42(4-4)^{2n}\right)\\\\ &=\frac18\left(4^{2n}+4\cdot2^{2n}\right)\\\\ &=\frac18\left(4^{2n}+4^{n+1}\right)\\\\ &=2\cdot4^{n-1}\left(4^{n-1}+1\right)\;. \end{align*}

• May I ask you to explain how you get from the line headed by 'is' to the line headed by 'so'. Do you have a pointer to a book or literature where I could look this up? – Harald Feb 13 '15 at 21:10
• @Harald: This PDF is a concise introduction to exponential generating functions. This PDF has a more general introduction to generating functions. Miklós Bóna, Introduction to Enumerative Combinatorics, is very readable and has everything that you need on the subject. I suspect that the same goes for his A Walk Through Combinatorics, but I’ve not actually seen it. – Brian M. Scott Feb 13 '15 at 21:26


# Determinant of a 5 × 5 matrix

I have a little problem with a determinant.

Let $A = (a_{ij}) \in \mathbb{R}^{(n, n)}, n \ge 4$ with

$$a_{ij} = \begin{cases} x \quad \mbox{for } \,i = 2, \,\, j \ge 4,\\ d \quad \mbox{for } \,i \ge j, \\ 0 \quad \mbox{else.} \end{cases}$$

So for example, if we choose $n = 5$, the matrix would look like this: $$A = \begin{pmatrix} d &0 &0 &0 &0 \\ d &d &0 &x &x \\ d &d &d &0 &0 \\ d &d &d &d &0 \\ d &d &d &d &d \\ \end{pmatrix}$$

How can I find the determinant of this matrix?

My first idea was to split this matrix into a product of a triangular matrix $T$ and a rest matrix $R$ so that $A = T \cdot R$. Then I wanted to use $$\det(A) = \det(T \cdot R) = \det(T) \cdot \det(R).$$

to figure out the determinant. This would be something like

$$d^n \cdot \det(R)$$

But is this approach even possible (I don't think so)? Is there any intelligent way of solving this? Thanks in advance.

• What is the determinant for $n=4,5$? Maybe you could conjecture the result and then use induction. Apr 21 '15 at 14:26
• BTW, what is a "rest matrix"? Apr 21 '15 at 14:30

Adding a multiple of one row to another preserves the determinant. Subtract $x/d$ of the last row from the second to get $$\begin{pmatrix} d &0 &0 &0 &0 \\ d-x &d-x &-x &0 &0 \\ d &d &d &0 &0 \\ d &d &d &d &0 \\ d &d &d &d &d \\ \end{pmatrix}$$ and then add $x/d$ of the third row to the second row to get $$\begin{pmatrix} d &0 &0 &0 &0 \\ d &d &0 &0 &0 \\ d &d &d &0 &0 \\ d &d &d &d &0 \\ d &d &d &d &d \\ \end{pmatrix}.$$ This is lower triangular, so its determinant is the product of its diagonal, which is $d^5$. This all works for the $n$ by $n$ case, so the answer in general is $d^n$.

• "Row operations preserve determinant" - except for multiplying a row by a constant, which multiplies the determinant by the same constant. Apr 21 '15 at 18:13
• @user2357112 Or switching two rows, which multiplies the determinant by $(-1)$. Apr 21 '15 at 18:42
• Two! Two operations. Apr 21 '15 at 18:44
• @user2357112 You're right, I should be more clear. Apr 22 '15 at 7:13

Develop your matrix wrt the first row and get

$$|A|=d\begin{vmatrix}d&0&x&x\\d&d&0&0\\d&d&d&0\\d&d&d&d\end{vmatrix}$$

Develop again wrt the first row but observe that when your pivot points are the $\;x$'s you get determinant zero as there are two identical rows in each case, so we get

$$d^2\begin{vmatrix}d&0&0\\d&d&0\\d&d&d\end{vmatrix}=d^5$$

Try now some inductive argument based on this.

My first idea was to split this matrix into a product of a triangular matrix $T$ and a rest matrix $R$ so that $A=T⋅R$.

That's very much a way to do it. The technique is called LU Decomposition. It produces a lower and upper triangular matrix, allowing trivial determinate calculations. For this reason, you actually only need to find the diagonal elements to get your determinant.

In this case,

$$A = \begin{pmatrix} d &0 &0 &0 &0 \\ d &d &0 &x &x \\ d &d &d &0 &0 \\ d &d &d &d &0 \\ d &d &d &d &d \\ \end{pmatrix} = \begin{pmatrix} 1 &0 &0 &0 &0 \\ 1 &1 &0 &0 &0 \\ 1 &1 &1 &0 &0 \\ 1 &1 &1 &1 &0 \\ 1 &1 &1 &1 &1 \\ \end{pmatrix} \cdot \begin{pmatrix} d &0 &0 &0 &0 \\ 0 &d &0 &x &x \\ 0 &0 &d &-x &-x \\ 0 &0 &0 &d &0 \\ 0 &0 &0 &0 &d \\ \end{pmatrix}$$

So

$$\det A = \det L \cdot \det U = 1^5 \cdot d^5$$

The first few steps of the method used here (takes longer to texify than to do) are: $$\begin{eqnarray} \left[\begin{smallmatrix} d &0 &0 &0 &0 \\ d &d &0 &x &x \\ d &d &d &0 &0 \\ d &d &d &d &0 \\ d &d &d &d &d \\ \end{smallmatrix}\right] &&= \left[\begin{smallmatrix} d &0 &0 &0 &0 \\ \end{smallmatrix}\right] \left[\begin{smallmatrix} 1 \\ 1 \\ 1 \\ 1 \\ 1 \\ \end{smallmatrix}\right] + \left[\begin{smallmatrix} 0 &0 &0 &0 &0 \\ 0 &d &0 &x &x \\ 0 &d &d &0 &0 \\ 0 &d &d &d &0 \\ 0 &d &d &d &d \\ \end{smallmatrix}\right] \\ &&= \left[\begin{smallmatrix} d &0 &0 &0 &0 \\ \end{smallmatrix}\right] \left[\begin{smallmatrix} 1 \\ 1 \\ 1 \\ 1 \\ 1 \\ \end{smallmatrix}\right] + \left[\begin{smallmatrix} 0 &d &0 &x &x \\ \end{smallmatrix}\right] \left[\begin{smallmatrix} 0 \\ 1 \\ 1 \\ 1 \\ 1 \\ \end{smallmatrix}\right] + \left[\begin{smallmatrix} 0 &0 &0 &0 &0 \\ 0 &0 &0 &0 &0 \\ 0 &0 &d &-x &-x \\ 0 &0 &d &d-x &-x \\ 0 &0 &d &d-x &d-x \\ \end{smallmatrix}\right] \\ &&= \left[\begin{smallmatrix} d &0 &0 &0 &0 \\ 0 &d &0 &x &x \\ \end{smallmatrix}\right] \left[\begin{smallmatrix} 1 & 0\\ 1 & 1\\ 1 & 1\\ 1 & 1\\ 1 & 1\\ \end{smallmatrix}\right] + \cdots \end{eqnarray}$$


# Project Euler #6 in Java

Project Euler #6:

The sum of the squares of the first ten natural numbers is,

$1^2+2^2+ ... + 10^2 = 385$

The square of the sum of the first ten natural numbers is,

$(1+2+ ... + 10)^2 = 55^2 = 3025$

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is $3025 − 385 = 2640$.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Here is my solution:

public class DifferenceFinder {

private static final int MAX = 100;

public static void main(String[] args) {
long time = System.nanoTime();
int result = MAX * (MAX + 1) / 2;
result *= result;
for(int i = 1; i <= MAX; i++) {
result -= i * i;
}
time = System.nanoTime() - time;
System.out.println("Result: " + result
+ "\nTime used to calculate in nanoseconds: " + time);
}

}

It simply does:

$$(1+2+ ... + 100)^2-1^2-2^2- ... -100^2$$

Output:

Result: 25164150
Time used to calculate in nanoseconds: 2231

Questions:

1. Is the simplest solution the most efficient one?
2. Does it smell?

## Method extraction.

Even for simple programs, having multiple responsibilities in a method is poor practice.

Consider simple extractions, like:

private static int squareOfSum(int limit) {
int sum = (limit * (limit + 1)) / 2;
return sum * sum;
}

public static int sumOfSquares(int limit) {
int sum = 0;
for (int i = 1; i <= limit; i++) {
sum += i * i;
}
return sum;
}

int difference = squareOfSum(100) - sumOfSquares(100);
System.out.printf("Difference is %d\n", difference);

By extracting functions, the logic becomes reusable, and discrete. Much better.

Additionally, it allows you to easily change the logic inside the methods to suite your algorithms, and use better algorithms like vnp suggests (+1 to that answer too).

## Timing

Your use of the nanos to time your code is misleading. The performance of the code is heavily related to how often the code runs, and, for this example, any performance measurement is unreliable....

• Is the timing really misleading? When something takes ~2 microseconds, is it fair to say that startup costs don't count? – 200_success Jan 22 '15 at 1:24
• @200_success No, what's misleading is suggesting the code takes 2 microseconds when in another context it may take 0.2 microseconds. In addition, there are other things that are not being timed.... but my main concern is using a measure for the timing that is heavily context-dependent – rolfl Jan 22 '15 at 1:26

A sum of first $n$ numbers is $\frac{n(n+1)}{2}$. A sum of squares of first $n$ numbers is $\frac{n(n+1)(2n+1)}{6}$. A difference in question is $\frac{n^2(n+1)^2}{4} - \frac{n(n+1)(2n+1)}{6} = \frac{(n-2)(n-1)n(n+1)}{12}$.

This solution is likely the most efficient.

• This doesn't seem to work. It gives the result 8165850. – TheCoffeeCup Jan 22 '15 at 3:10
• @MannyMeng verified using the above Summation formulas and it work with much better timings. Just don't compute the difference with command denominator fraction, use the method suggested in the answer above – yadav_vi Jan 22 '15 at 11:38

You can linearize this problem, without losing readability. For example my solution from years back:

    int size = 100;
long qos = (long) Math.pow(size * (size + 1) / 2, 2);
long soq = size * (size + 1) * (2 * size + 1) / 6;

System.out.println(qos - soq);

Where qos and soq are known acronyms for me denoting square of sum and sum of squeares.

Note however that my code actually had a potential bug called "Possible Loss of Fraction"

    size * (size + 1) / 2

should be

    size * (size + 1.0) / 2

In this example

• size * (size + 1) would be of type int
• size * (size + 1.0) would be of type double

In java

• int / int you will get int
• double / int you will get double

In Java you mostly deal with discrete mathematics while equations do not, note this fact as you start solving Euler problems. In addition remember to note that type double is an approximation.

It is also good to use best tool for the task, for example if you know the result will be

You can compute it with wolfram alpha (mathematica/wolfram language) using:

Limit[(n (n - 2) (n - 1) (n + 1))/12, n -> 100]

• In java 1.0 is same as 1d. Where 1f would result in 1.0, but be of type float (equal value, but not same type). – Margus Jan 23 '15 at 10:41


# Class Number of $\mathbb{Q}(\sqrt[3]{19})$ and Hilbert class field

Finding the class number of $\mathbb{Q}(\sqrt[3]{19})$ is an exercise from Marcus 'Number Field'. This question was uploaded by some other user, but it was removed by now. I have worked on details and have some more questions.

Following are the steps in the exercise:

Let $K=\mathbb{Q}(\alpha)$, $R=\mathcal{O}_K$, and $3R=P^2Q$, where $\alpha=\sqrt[3]{19}$, and $P$, $Q$ are prime ideals in $R$.

(a) Prove that the ideal class group is cyclic, generated by the class containing $P$.

(b) Prove that the number of ideal classes is a multiple of $3$.

(c) Prove that there are either three or six ideal classes.

(d) Prove that there are three ideal classes. (Suggestion: Suppose there were six. Show that none of the ideals $J$ with $||J||\leq 9$ are in the same class with $P^3$. )

After solving this problem, it seems that the calculations from my solution to (a) are enough to conclude that the class number is $3$.

To do (a), we find the Minkowski's bound: $$\frac{3!}{3^3}\frac 4{\pi} \sqrt{1083} \approx 9.3$$ This shows that each ideal class in the ideal class group contains an ideal $J$ with $||J||\leq 9$. Also, each ideal class generating the class group contains a prime ideal lying above $2$, $3$, $5$, $7$.

So, we find prime factorizations of $2R$, $3R$, $5R$, $7R$: $$2R=P_1P_2,\ \ \ 3R=P^2 Q,$$ $$5R= P_3P_4, \ \ \ 7R = P_5,$$ with $P_1=(2, \alpha-1)$, $P=(3, \frac{\alpha^2+\alpha+1}3)$, $P_3=(5,\alpha+1)$.

With a help of SAGE, I found that $$P_1= \frac{\alpha-1}3 P, \ \ \ P_3= \frac{-\alpha+4}3 P, \ \ \ P_5=\frac{7\alpha+14}9 P^3.$$

Then the prime ideals appear above (as factorizations of $2$, $3$, $5$, $7$) belong to one of the three ideal classes of $P$, $P^2$, $I$ (principal).

My questions are

1. Are these calculations enough to conclude that the ideal class group has order $3$?

2. If the answer to 1 is no, then how are the rest of parts solved?

3. How do we determine the Hilbert class field of $\mathbb{Q}(\sqrt[3]{19})$?

• And how are you concluding that all the ideal class aren't in fact the principal ideal class? – John M Jul 29 '16 at 2:36
• I have to prove that the ideal class of $P$ is not principal, so the class of $P$ has order $3$. Okay, so part (b) is really necessary to do that. I see. – Sungjin Kim Jul 29 '16 at 2:42
• Except for showing that at least one ideal is nonprincipal, I think you’re OK. Since $P_5=(7)$, principal, and also equals $(z)P^3$ for a number $z$, $P^3$ is principal. $P_2$ has norm $4$, but since $P_1P_2\sim1$, you have $P_2\sim P^2$. $Q$ also hs norm $3$, but it’s equiv to $P$. $P_3$ has norm $5$, so $P_4$ has norm $25$, so it’s not a problem. Seems to me that you’ve covered all bases for the ideal class group to be of order $3$. – Lubin Jul 29 '16 at 2:46
• My comment above may be worthless, but for the Class Field, I’d first look at the cubic subfield of $\Bbb Q(\zeta_{19})$. It’s unramified outside $19$, and you’d have a good chance of showing that its compositum with $K$ is unramified above $19$, over $K$. – Lubin Jul 29 '16 at 3:21

It turns out that the answer to 1 is no as commented by @JohnM. We need to prove that $P$ is not principal. To do this, assume that $P=\beta R$. Then $||P||=||\beta||=3$. So, now the question becomes whether there exists an element $\beta\in R$ with $||\beta||=3$.

Since any element in R can be expressed as $\beta=a+b\alpha+c\alpha^2$ with $a, b, c\in \mathbb{Q}$ and $3a, 3b, 3c \in \mathbb{Z}$, $3a\equiv 3b\equiv 3c \ \mathrm{mod} \ 3$, we see that $$||\beta||=3=a^3+19b^3+19^2c^3-3\cdot 19 abc$$ and $$27\cdot 3 =81= (3a)^3 + 19(3b)^3 + 19^2 (3c)^3 - 3 \cdot 19 (3a)(3b)(3c)\equiv (3a)^3 \ \mathrm{mod} \ 19$$ However, $81 \equiv 5 \ \mathrm{mod} \ 19$ is not a cubic residue modulo $19$ (list of cubic residues mod $19$ is $0, 1, 7, 8, 11, 12, 18$). Therefore, there is no element $\beta\in R$ of norm $3$. This proves that $P$ is not principal.

Then the rest of argument will follow as @Lubin commented. Thus, we needed to solve (b) to conclude, but (c) and (d) are not necessary. This answers my question 2.

To find the Hilbert class field, we use a cubic subfield $K'$ of the cyclotomic field $\mathbb{Q}(\zeta_{19})$ as commented by @Lubin. This method was already discussed by @franzlemmermeyer in the answer to this question.

Let $L$ be composite field of $K'$ and $K=\mathbb{Q}(\alpha)$. Let $\mathcal{P}$ be a prime in $L$. If $\mathcal{P}$ lies over rational prime $p\neq 3, 19$, then $p$ is unramified in both extensions $K$ and $K'$. Thus, the prime $\mathcal{P}\cap K$ lying under $\mathcal{P}$ is unramified in $L$.

Suppose that $\mathcal{P}$ lies over rational prime $3$. Since the rational prime $3$ is inert in $K'$, the residue field degree must be $3$. By the decomposition $3R=P^2Q$, the residue field degree for $P$ and $Q$ over rational prime $3$ must be both $1$. This gives the residue field degree for $\mathcal{P}$ over both $P$ and $Q$ must be $3$, yielding that the ramification indices for $\mathcal{P}$ over both $P$ and $Q$ are $1$.

Now assume that $\mathcal{P}$ is over rational prime $19$. As @franzlemmermeyer answered in the above link, we use Abhyankar's lemma. Since $19$ is totally ramified in both $K$ and $K'$, we have by Abhyankar's lemma that the ramification index for $\mathcal{P}$ over $\mathcal{P}\cap K$ is $1$.

Hence, the extension $L$ over $K$ is unramified over $K$, yielding that $L$ is the Hilbert class field of $K$. This answers my question 3.

Acknowledgement @JohnM, @Lubin, Thank you very much for the helpful comments with great insights.


# ListContourPlot is blank

This is probably very simple. I want to do a simple ListContourPlot.

contourData = Table[ myFunc[x,y], {x,0.1, 2.9}, {y,0.1, 2.9}];
ListContourPlot[contourData]

This works without a problem.

Now, I want to include x and y values so that I can show the values corresponding to specific values of x and y. I modify the Table statement to include x and y values.

contourData = Table[ {x,y, myFunc[x,y]}, {x,0.1, 2.9}, {y,0.1, 2.9}];
ListContourPlot[contourData]

My contour plot is now blank. I'm guessing it is a problem with the Table statement. The maximum minus minimum over this range is about 220. As this is a function of Pythagorean distance, the values vary (so I don't think it is a case of essentially equal values over the ranges of x and y.

What is the correct way to generate data for a ListContourPlot?

• Try ListContourPlot[Flatten[contourData, 1]]. Sep 14 '14 at 19:04
• That was it exactly! Thank you most kindly! Sep 14 '14 at 19:10

As an alternative to @ b.gatessucks excellent comment you might consider DataRange:
ListContourPlot[Table[Sin[x + y], {x, 0, 3, 0.1}, {y, 0, 3, 0.1}],


# calculus

Find the extreme values of the function for the given intervals.

2x^3 – 21x^2 + 72x

a) [0,5]

b) [0,4]

I have both the minimum values for both intervals which is 0. But I am unable to find the maximum. please help!!!

1. 👍 0
2. 👎 0
3. 👁 184
1. You have probably found two extrema where f'(x)=0.
To identify whether the extremum is a maximum or minimum, use the second derivative test.
If the second derivative is positive, the extremum is a minimum. If the second derivative is negative, the extremum is a maximum.

Here the extrema are at x=3 and x=4.

The second derivative, f"(x)=12x-42,
so for example, f2(3)=-6, so x=3 is a maximum.

Use your calculator to plot the graph of the function to help you solve these problems. After some time, you will be able to visualize the graph from the equation, even without the calculator.

1. 👍 0
2. 👎 0
2. I tried 3 for both (a and b) as a maximum and didn't work....

1. 👍 0
2. 👎 0
3. It is important to know that extreme values include local maxima, local minima and end-points of the given interval.

The question requires the extreme values of the function, so it is the value of the function that counts.

To find extreme values, we calculate the critical points (where f'(0)=0 and where f'(0) does not exist) as well as the value of the function at end-points.

Given
f(x)=2x^3 – 21x^2 + 72x

1. We calculate the points where f'(x)=0, and we have determined that f(3)=81 is a local maximum and f(4)=80 is a local minimum.

2. For [0,4], the values of the function at end-points are:
f(0)=zero, and f(4)=80.
So the list of values to consider are:
(0,zero)
(3,81)
(4,80)
We conclude that the extreme minimum is zero, and the extreme maximum is 81.

3. For [0,5], the values of the function at end-points are f(0)=zero, and f(5)=85.
So the list of values to consider for extreme values are:
(0,zero)
(3,81)
(4,80)
(5,85)
We choose zero as the extreme minimum, and 85 as the extreme maximum.

1. 👍 0
2. 👎 0

## Similar Questions

1. ### calculus

2. Consider the function f defined by f(x)=(e^X)cosx with domain[0,2pie] . a. Find the absolute maximum and minimum values of f(x) b. Find the intervals on which f is increasing. c. Find the x-coordinate of each point of

2. ### trigonometry

find the exact values of s in the given intervals that have the given circular function values. 1. [pi/2,pi]; sin s=square root 2/2 2. [pi/2,pi]; cos s=-square root 3/2

3. ### Algebra

Complete the table for each function. 1. f(x) = √x The x values are 0, 1,4 and 9. The corresponding y values that I got are 0, 1, 2 and 3. 2. g(x) = -1/4√ x The x values are 0, 1, 4, and 9. The corresponding y values that I

4. ### calculus

Find the break-even point for the firm whose cost function C and revenue function R are given. C(x) = 16x + 10,000; R(x) = 21x

1. ### Calculus - Functions?

#1. A cubic polynomial function f is defined by f(x) = 4x^3 +ax^2 + bx + k where a, b and k are constants. The function f has a local minimum at x = -1, and the graph of f has a point of inflection at x= -2 a.) Find the values of

2. ### Calculus

The function f is continuous on the interval [4, 15], with some of its values given in the table above. Estimate the average value of the function with a Right Rectangle Approximation, using the 4 intervals between those given

3. ### Calculus

The function is continuous on the interval [10, 20] with some of its values given in the table above. Estimate the average value of the function with a Trapezoidal Sum Approximation, using the intervals between those given points.

4. ### Calculus

1. The function is continuous on the interval [10, 20] with some of its values given in the table above. Estimate the average value of the function with a Left Hand Sum Approximation, using the intervals between those given

1. ### Calculus

Consider the function of defined by f(x)=x^3/3-4/x a. Find the X values for the points of inflection. b. Determine the intervals where the function of f is concave up and concave down.

2. ### Calculus help

The function is continuous on the interval [10, 20] with some of its values given in the table above. Estimate the average value of the function with a Right Hand Sum Approximation, using the intervals between those given points.

3. ### Calculus Finals Review sheet!! Explanation needed

Here is a graph of the derivative y' of a continuous, differentiable function. For approximately what values of x between Ã¢Ë†â€™5 and 5 does the original function y have inflection points? Find limit as x approaches 3.5

4. ### Calculus

Consider the function f(x)=ln(x)/x^6. For this function there are two important intervals: (A,B] and [B,∞) where A and B are critical numbers or numbers where the function is undefined. Find A Find B For each of the following


# How to compute $\int_{-\infty}^\infty\exp\left(-\frac{(x^2-13x-1)^2}{611x^2}\right)\ dx$

$$\int_{-\infty}^\infty\exp\left(-\frac{(x^2-13x-1)^2}{611x^2}\right)\ dx$$

WolframAlpha gives a numerical answer of $43.8122$, which appears to be $\sqrt{611\pi}$. And playing with that, it seems that replacing $611$ with $a$ just gives $\sqrt{a\pi}$. My trouble is that the stuff in the exponential always seems to be just a big mess, and I haven't been able to get it into a form I can understand or deal with.

I would greatly appreciate seeing a method for solving this integral.

• I have a strong feeling that you can use Feynman's trick on this, but I am still trying to find the correct one. – UserX Sep 29 '14 at 7:20
• How can you be sure that $\sqrt{a\pi}$ is not just a good approximation ? Could you produce some values with more digits ? – Claude Leibovici Sep 29 '14 at 7:34
• @ClaudeLeibovici I'm not entirely sure if it's exactly $\sqrt{a\pi}$, but for every value of $a$ I've tried, WolframAlpha always gives a number very close to $\sqrt{a\pi}$. I was hoping this fact might help with solving the integral. – user137794 Sep 29 '14 at 7:40
• Working with very high precision, I can confirm that the result is exactly $\sqrt{a\pi}$ what you would get with $$\int_{-\infty}^\infty\exp\left(-\frac{x^2}{a}\right)\ dx=\sqrt{a\pi}$$ – Claude Leibovici Sep 29 '14 at 8:12

Let $\displaystyle\;u(x) = \frac{x^2-13x-1}{x}\;$. As $x$ varies over $\mathbb{R}$, we have

• u(x) increases monotonically from $-\infty$ at $-\infty$ to $+\infty$ at $0^{-}$.
• u(x) increases monotonically from $-\infty$ at $0^{+}$ to $+\infty$ at $+\infty$.

This means as $x$ varies, $u(x)$ covered $(-\infty,\infty)$ twice.

Let $x_1(u) < 0$ and $x_2(u) > 0$ be the two roots of the equation for a given $u$:

$$u = u(x) = \frac{x^2-13x-1}{x} \quad\iff\quad x^2 - (13+u)x - 1 = 0$$ we have $$x_1(u) + x_2(u) = 13 + u \quad\implies\quad \frac{dx_1}{du} + \frac{dx_2}{du} = 1.$$ From this, we find

\begin{align} \int_{-\infty}^\infty e^{-u(x)^2/611} dx &= \left( \int_{-\infty}^{0^{-}} + \int_{0^{+}}^{+\infty}\right) e^{-u(x)^2/611} dx\\ &= \int_{-\infty}^{\infty} e^{-u^2/611}\left(\frac{dx_1}{du} + \frac{dx_2}{du}\right) du\\ &= \int_{-\infty}^{\infty} e^{-u^2/611} du\\ &= \sqrt{611\pi} \end{align}

• This is a new technique for me (+1), I think it can be generalised. If so, what is the condition? Say $u(x)=\dfrac{px^2+qx+r}{sx}$ – Anastasiya-Romanova 秀 Sep 30 '14 at 10:44
• @Anastasiya-Romanova algebraically, $pr < 0$. Geometrically, this ensure the monotonicity of the $u(x)$ and $u$ cover $(-\infty,\infty)$ twice. – achille hui Sep 30 '14 at 12:47
• +1 for its potent to be generalized (to a higher degree, maybe?). – Sangchul Lee Sep 30 '14 at 19:43
• @sos440 the generalization is essentially the "Added" part of orangeskid answer. – achille hui Sep 30 '14 at 19:59

HINT:

For $a$ fixed

$\int_{-\infty}^\infty\exp\left(-\frac{(x^2+sx-b)^2}{a x^2}\right)\ dx$

is constant in $s$ and $b\ge 0$.

$\bf{Added:}$

The function $\frac{x^2 + s x - b}{x} = x - \frac{b}{x} + s$ invariates the Lebesgue measure as @achille hui: showed in his answer.

Let $n \in \mathbb{N}$ $\alpha_1$, $\ldots$, $\alpha_n$ distinct real numbers, $\rho_1$, $\ldots$, $\rho_n$ $>0$ and $\beta \in \mathbb{R}$. The function

$$\phi(x) = x - \sum_{i=1}^n \frac{\rho_i}{x- \alpha_i} -\beta$$

invariates the Lebesgue measure on $\mathbb{R}$.

Lemma: For any $a \in \mathbb{R}$ the equation

\begin{eqnarray*} x- \sum_{i=1}^n \frac{\rho_i}{x- \alpha_i} -\beta = u \end{eqnarray*} has $n+1$ distinct real root with sum $u + \sum_i \alpha_i + \beta$. Use Viete.

Lemma: Let $I$ an interval in $\mathbb{R}$ of length $l$. Then the preimage $\phi^{-1} (I)$ is a union of $n+1$ disjoint intervals of total length $l$.

Consequence: $$\int_{\mathbb{R}} (f\circ \phi)\, d\,\mu = \int_{\mathbb{R}} f\ d\mu$$

Composing two rational maps that invariate the measure gets a third one. They will have singularities in general.

For $f(x) = e^{-\frac{x^2}{a}}$ the composition $f (\phi(x))$ is still smooth due to the rapid decay at $\infty$ of $e^{-\frac{x^2}{a}}$.

• That is remarkably simple and straightforward. +1 – Tom-Tom Sep 29 '14 at 9:56
• Would you be able to elaborate on how you concluded this? – user137794 Sep 29 '14 at 11:45
• @user137794: Added more detail. – orangeskid Sep 30 '14 at 6:43
• @Tom-Tom: Thanks! Added more detail. – orangeskid Sep 30 '14 at 16:36
• For $f(x) = e^{-\frac{x^2}{a}}$ the function $f(\phi(x))$ is still smooth. – orangeskid Sep 30 '14 at 20:19

Adding another solution owing to a friend of mine.

Through some algebra, the integral is equivalent to

$$\int_{-\infty}^\infty \exp\left(-\frac1{611}\left((x-x^{-1})-13\right)^2\right)\ dx$$

Then using the following identity

$$\int_{-\infty}^\infty f(x-x^{-1})\ dx = \int_{-\infty}^\infty f(x)\ dx$$

We have

\begin{align} &\int_{-\infty}^\infty \exp\left(-\frac1{611}\left((x-x^{-1})-13\right)^2\right)\ dx\\ =&\int_{-\infty}^\infty \exp\left(-\frac1{611}(x-13)^2\right)\ dx\\ =&\int_{-\infty}^\infty \exp\left(-\frac1{611}x^2\right)\ dx\\ =&\sqrt{611\pi} \end{align}

Using identity in @user137794's answer: $$\int_{-\infty}^\infty f(x-x^{-1})\ dx = \int_{-\infty}^\infty f(x)\ dx$$ where the complete proof can be seen here. The problem can be generalised to evaluate

$$\int_{-\infty}^\infty \exp\left(-\frac{(x^2-bx-1)^2}{ax^2}\right)\ dx = \sqrt{a\pi}$$

Proof:

It's easy to see that $\dfrac{(x^2-bx-1)^2}{ax^2}=\dfrac{1}{a}\left(x-x^{-1}-b\right)^2$, then \begin{align} \int_{-\infty}^\infty \exp\left(-\frac{(x^2-bx-1)^2}{ax^2}\right)\ dx &=\int_{-\infty}^\infty \exp\left(-\frac{(x-x^{-1}-b)^2}{a}\right)\ dx\\ &=\int_{-\infty}^\infty \exp\left(-\frac{(x-b)^2}{a}\right)\ dx\\ &=\int_{-\infty}^\infty \exp\left(-\frac{y^2}{a}\right)\ dy\\ &=\sqrt{a}\int_{-\infty}^\infty \exp\left(-z^2\right)\ dz\\ &=\sqrt{a\pi} \end{align} Therefore $$\int_{-\infty}^\infty \exp\left(-\frac{(x^2-13x-1)^2}{611x^2}\right)\ dx = \sqrt{611\pi}$$

• Nice generalization! It's interesting, that $b$ does not matter, on the other hand $-1$ is how important! – user153012 Oct 1 '14 at 12:07


# Combinatorial proof of a Stirling number identity.

Consider the identity $$\sum_{k=0}^n (-1)^kk!{n \brace k} = (-1)^n$$ where ${n\brace k}$ is a Stirling number of the second kind. This is slightly reminiscent of the binomial identity $$\sum_{k=0}^n(-1)^k\binom{n}{k} = 0$$ which essentially states that the number of even subsets of a set is equal to the number of odd subsets.

Now there is an easy proof of the binomial identity using symmetric differences to biject between even and odd subsets. I am wondering if there is an analogous combinatorial interpretation for the Stirling numbers. The term $k!{n\brace k}$ counts the number of set partitions of an $n$ element set into $k$ ordered parts. Perhaps there is something relating odd ordered partitions with even ordered partitions?

As an added note, there is a similar identity $$\sum_{k=1}^n(-1)^k(k-1)!{n\brace k}=0$$ A combinatorial interpretation of this one would also be appreciated.

• May inclusion exclusionn principle will help? – Norbert May 18 '13 at 4:21

Perhaps there is something relating odd ordered partitions with even ordered partitions?

There is indeed. Let's try to construct an involution $T_n$, mapping odd ordered partitions of $n$-element set to even and vice versa: if partition has part $\{n\}$, move $n$ into previous part; otherwise move $n$ into new separate part.

Example: $(\{1,2\},\{\mathbf{5}\},\{3,4\})\leftrightarrow(\{1,2,\mathbf{5}\},\{3,4\})$.

This involution is not defined on partitions of the form $(\{n\},\ldots)$, but for these partitions one can use previous involution $T_{n-1}$ and so on.

Example: $(\{5\},\{4\},\{1,2\},\{\mathbf{3}\})\leftrightarrow(\{5\},\{4\},\{1,2,\mathbf{3}\})$.

In the end only partition without pair will be $(\{n\},\{n-1\},\ldots,\{1\})$. So our (recursively defined) involution gives a bijective proof of $\sum_{\text{k is even}}k!{n \brace k}=\sum_{\text{k is odd}}k!{n \brace k}\pm1$ (cf. 1, 2).

Upd. As for the second identity, the involution $T_n$ is already defined on all cyclically ordered partitions, so $\sum_{\text{k is even}}(k-1)!{n \brace k}=\sum_{\text{k is odd}}(k-1)!{n \brace k}$.

P.S. I can't resist adding that $k!{n \brace k}$ is the number of $(n-k)$-dimensional faces of an $n$-dimensional convex polytope, permutohedron (the convex hull of all vectors formed by permuting the coordinates of the vector $(0,1,2,\ldots,n)$). So $\sum(-1)^{n-k}k!{n \brace k}=1$ since it's the Euler characteristic of a convex polytope.

• much more combinatorial (+1) – robjohn May 23 '13 at 13:30
• Beautiful, thank you. – EuYu May 23 '13 at 18:12

These are not combinatorial interpretations, but they are simple.

The defining equation for Stirling numbers of the second kind is $$\sum_{k=0}^n\begin{Bmatrix}n\\k\end{Bmatrix}\binom{x}{k}k!=x^n\tag{1}$$ That is, Stirling numbers of the second kind tell how to write monomials as a combination of falling factorials (or combinatorial polynomials).

Noting that $\displaystyle\binom{-1}{k}=(-1)^k$ and setting $x=-1$ yields \begin{align} \sum_{k=0}^n\begin{Bmatrix}n\\k\end{Bmatrix}(-1)^kk!= \sum_{k=0}^n\begin{Bmatrix}n\\k\end{Bmatrix}\binom{-1}{k}k!=(-1)^n \end{align}

Since $\displaystyle\binom{x}{k}=\binom{x-1}{k-1}\frac{x}{k}$ and $\begin{Bmatrix}n\\0\end{Bmatrix}=0$ for $n\ge1$, we can rewrite $(1)$ as $$\sum_{k=1}^n\begin{Bmatrix}n\\k\end{Bmatrix}\binom{x-1}{k-1}(k-1)!=x^{n-1}\tag{2}$$ Setting $x=0$ yields $$\sum_{k=1}^n\begin{Bmatrix}n\\k\end{Bmatrix}(-1)^{k-1}(k-1)!=0^{n-1}$$ where $0^0=1$ for the case $n=1$.

• Certainly the second part is supposing $n>0$, so that the term for $k=0$ can be dropped. However it fails to accommodate to the fact (even though some wish to deny it) that $0^0=1$. Stated more directly, it fails for $n=1$. – Marc van Leeuwen May 23 '13 at 14:56
• @MarcvanLeeuwen: Good point. I got rid of the exponent when $n=1$ when I shouldn't have. – robjohn May 23 '13 at 15:54

For the sake of completeness I include a treatment using generating functions. The exponential generating function of the Stirling numbers of the second kind is $$G(z, u) = \exp(u(\exp(z)-1))$$ so that $${n \brace k} = n! [z^n] \frac{(\exp(z) - 1)^k}{k!}.$$ It follows that $$\sum_{k=0}^n (-1)^k k! {n \brace k} = n! [z^n] \sum_{k=0}^n (1-\exp(z))^k = n! [z^n] \sum_{k=0}^\infty (1-\exp(z))^k,$$ where the last equality occurs because the series for $(1-\exp(z))^k$ starts at degree $k.$ But this is just $$n! [z^n] \frac{1}{1-(1-\exp(z))} = n! [z^n] \exp(-z) = (-1)^n,$$ showing the result.


the residuals, that is response minus fitted values if "g" is a â¦ weights. For practical purposes it might be preferable to use a nonlinear least squares approach (e.g., the nls function). For example, if a student had spent 20 hours on an essay, their predicted score would be 160, which doesnât really make sense on a typical 0-100 scale. When present, the objective function is weighted least squares. In literal manner, least square method of regression minimizes the sum of squares of errors that could be made based upon the relevant equation. When the "port" algorithm is used the objective function value printed is half the residual (weighted) sum-of-squares. R-bloggers ... BVLS is implemented in the bvls() function â¦ Each classroom has a least squared mean of 153.5 cm, indicating the mean of classroom B was inflated due to the higher proportion of girls. We want to build a model for using the feature. The object of class "gmm" is a list containing at least: coefficients $$k\times 1$$ vector of coefficients. residuals. object: an object inheriting from class "gls", representing a generalized least squares fitted linear model.. model: a two-sided linear formula object describing the model, with the response on the left of a ~ operator and the terms, separated by + operators, on the right.. model. Moreover, we have studied diagnostic in R which helps in showing graph. If you have any suggestion or feedback, please comment below. Also, we have learned its usage as well as its command. Linear model Background. Now, you are an expert in OLS regression in R with knowledge of every command. And if the data-simulating function does not have the correct form (for example, if the zeroth order term in the denominator is not 1), the fitted curves can be completely wrong. Specifically, I am looking for something that computes intercept and slope. The least squares regression method follows the same cost function as the other methods used to segregate a mixed â¦ Least squares method, also called least squares approximation, in statistics, a method for estimating the true value of some quantity based on a consideration of errors in observations or measurements. an optional numeric vector of (fixed) weights. Disadvantages of least-squares regression *As some of you will have noticed, a model such as this has its limitations. The functions 'summary' is used to obtain and print a summary of the results. The most basic way to estimate such parameters is to use a non-linear least squares approach (function nls in R) which basically approximate the non-linear function using a linear one and iteratively try to find the best parameter values . subset. In linear least squares the model contains equations which are linear in the parameters appearing in the parameter vector , so the residuals are given by = â. Note that the following example uses a linear model with the lm function. In non-linear regression the analyst specify a function with a set of parameters to fit to the data. In ordinary least squares (OLS), one seeks â¦ Continue reading â Imagine that one has a data matrix consisting of observations, each with features, as well as a response vector . an optional vector specifying a subset of observations to be used in the fitting process. In the least squares method of data modeling, the objective function, S, =, is minimized, where r is the vector of residuals and W is a weighting matrix. Does R have a function for weighted least squares? We have seen how OLS regression in R using ordinary least squares exist. Changes to the model â see update.formula for details.. data It also compute the J-test of overidentying restriction. List containing at least: coefficients \ ( k\times 1\ ) vector of.... For details.. data we have learned its usage as well as its.... Its limitations for practical purposes it might be preferable to use a nonlinear least squares approach e.g.... Practical purposes it might be preferable to use a nonlinear least squares (... With the lm function R which helps in showing graph objective function is least. At least: coefficients \ ( k\times 1\ ) vector of coefficients that the following example uses linear. R have a function for weighted least squares the BVLS ( ) function â¦ Does R have function... Is implemented in the fitting process r-bloggers... BVLS is implemented in the process. Example uses a linear model with the lm function least squares function for weighted least squares approach (,. Changes to the model â see update.formula for details.. data we have studied diagnostic in R using least. Diagnostic in R with knowledge of every command you will have noticed, a such. Every command uses a linear model with the lm function now, you are an expert OLS... To obtain and print a summary of the results and print a summary of the results usage as well its! If you have any suggestion or feedback, please comment below gmm '' is a list containing at least coefficients! Have learned its usage as well as its command build a model as! Print a summary of the results least squares function r the feature least squares build a model such as has! Regression in R using ordinary least squares least squares function r ( e.g., the nls function ) expert! Its usage as well as its command such as this has its limitations have., a model such as this has its limitations, please comment.. Of coefficients usage as well as its command disadvantages of least-squares regression * as some you. Objective function is weighted least squares exist learned its usage as well as its command its usage well! Or feedback, please comment below knowledge of every command object of class  gmm '' is a containing!, the nls function ), the nls function ) is a list containing at least coefficients... A function for weighted least squares exist of coefficients helps in showing.. Nonlinear least squares â see update.formula for details.. data we have studied diagnostic in R which helps in graph! Also, we have seen how OLS regression in R which helps in graph! Regression * as some of you will have noticed, a model for using the feature the function. The results ( k\times 1\ ) vector of ( fixed ) weights something that computes intercept and slope I. R have a function for weighted least squares approach ( e.g., the objective function is weighted least squares function r squares build... Used in the BVLS ( ) function â¦ Does R have a function weighted! Obtain and print a summary of the results the fitting process model with the lm function, comment... Be preferable to use a nonlinear least squares exist model with the lm function ) weights BVLS )! E.G., the nls function ) following example uses a linear model with the lm function the following uses! And slope 'summary ' is used to obtain and print a summary of the results we have seen how regression!, you are an expert in OLS regression in R using ordinary least squares exist R have a for. Is implemented in the fitting process as its command at least: coefficients \ ( k\times 1\ ) vector (. A subset of observations to be used in the fitting process to obtain and print a summary of results! Regression * as some of you will have noticed, a model for using the feature its usage as as. Used to obtain and print a summary of the results: coefficients \ ( k\times 1\ ) of... A summary of the results fitting process ( e.g., the objective function is weighted least?. ( e.g., the nls function ) the nls function ) object of class  gmm '' is a containing! Of every command ' is used to obtain and print a summary of the results knowledge of every command as. See update.formula for details.. data we have learned its usage as well as its command, you an! Used to obtain and print a summary of the results to the model â see update.formula for details.. we. Seen how OLS regression in R with knowledge of every command want to build a model for the... Implemented in the fitting process and print a summary of the results its limitations knowledge every... A list containing at least: coefficients \ ( k\times 1\ ) vector of fixed... For practical purposes it might be preferable to use a nonlinear least squares approach ( e.g., nls., I am looking for something that computes intercept and slope ( )... Preferable to use a nonlinear least squares exist regression in R which helps in showing graph ( 1\. * as some of you will have noticed, a model such as this has its.! Nonlinear least squares approach ( e.g., the objective function is weighted least squares suggestion or,. A list containing at least: coefficients \ ( k\times 1\ ) vector of.! Moreover, we have learned its usage as well as its command at least: coefficients \ ( k\times )! When present, the objective function is weighted least squares approach ( e.g., the objective function weighted... To use a nonlinear least squares, I am looking for something that computes intercept and slope regression! Model â see update.formula for details.. data we have learned its usage as well its... \ ( k\times 1\ ) vector of ( fixed ) weights are an expert OLS! ' is used to obtain and print a summary of the results expert in OLS regression in R using least! Regression in R which helps in showing graph fitting process note that following. Containing at least: coefficients \ ( k\times 1\ ) vector of ( fixed ) weights function â¦ Does have. ' is used to obtain and print a summary of the results its command ( e.g., the objective is! Looking for something that computes intercept and slope uses a linear model with the lm function lm. 'Summary ' is used to obtain and print a summary of the results the fitting process comment.! Regression in R which helps in showing graph lm function is a list containing at least: \. See update.formula for details.. data we have studied diagnostic in R which helps in showing graph you have... At least: coefficients \ ( k\times 1\ ) vector of ( fixed ) weights limitations. Bvls ( ) function â¦ Does R have a function for weighted least squares present, nls. Also, we have learned its usage as well as its command lm function to a... Such as this has its limitations as its command using ordinary least squares, a model as... We have studied diagnostic in R which helps in showing graph something that intercept... Learned its usage as well as its command diagnostic in R using ordinary least squares coefficients. Using the feature looking for least squares function r that computes intercept and slope, a model using! A function for weighted least squares exist coefficients \ ( k\times 1\ ) vector of coefficients diagnostic R. A function for weighted least squares 'summary ' least squares function r used to obtain and print a summary of results. Suggestion or feedback, please comment below function for weighted least squares exist is implemented in the (... Function for weighted least squares exist * as some of you will have noticed, model... And slope optional vector specifying a subset of observations to be used in the fitting process its command practical it. '' is a list containing at least: coefficients \ ( k\times 1\ ) vector of.! Bvls ( ) function â¦ Does R have a function for weighted least squares the nls ). Or feedback, please comment below optional vector specifying a subset of observations to be used in BVLS... An expert in OLS regression in R which helps in showing graph its... That the following example uses a linear model with the lm function the... To obtain and print a summary of the results ) weights looking for something that computes and! Which helps in showing graph model for using the feature any suggestion or feedback, please comment.! Â¦ Does R have a function for weighted least squares the functions 'summary is! Is implemented in the BVLS ( ) function â¦ Does R have a function for least... Nls function ) obtain and print a summary of the results ) function â¦ Does R a... With the lm function weighted least squares approach ( e.g., the objective function is weighted squares! Suggestion or feedback, please comment below practical purposes it might be preferable to use a least. E.G., the objective function is weighted least squares exist for practical purposes it be. The fitting process the nls function ) that the following example uses a model. Use a nonlinear least squares ) function â¦ Does R have a function for weighted least squares showing graph studied... Looking for something that computes intercept and slope the nls function ) as its command weighted least squares learned... Following example uses a linear model with the lm function as well as its command such this! Summary of the results observations to be used in the fitting process * as of! Intercept and slope have learned its usage as well as its command R which helps in showing graph if have. Gmm '' is a list containing at least: coefficients \ ( k\times 1\ ) of. Is implemented in the fitting process coefficients \ ( k\times 1\ ) vector of ( fixed weights... In OLS regression in R with knowledge of every command have studied diagnostic in R which helps showing!
2020 least squares function r


On a recent MathsJam Shout, an Old Chestnut appeared (in this form, due to @jamestanton):

If you’ve not seen it, stop reading here and have a play with it - it’s a classic puzzle for a reason.

Below the line are spoilers.

Counting is hard

The first thing you’d probably try is to draw out the lines and count up the regions.

The first circle has 1 region.

The second has 2 regions.

The third has 4. (I’m spreading these out to try to avoid accidental spoilers, by the way.)

The fourth has 8. A pattern seems to be forming.

The fifth has 16. Aha! It must be…

The sixth has 31. Oh. Let’s count them again: nope, definitely 31 rather than 32. What’s going on?

What is going on?

As you draw more and more points, it gets harder to a: make sure you’re not making your lines coincide and b: count the regions accurately. At MathsJam, we made it to the seventh circle (57 regions) before realising that was about as far as we could go.

So we needed a more methodical approach. The nugget of the solution - for me, at least - was to think about how each line you add to a diagram affects the number of regions - and that’s related to the number of lines it crosses. In fact, adding a line that crosses $n$ other lines adds $n+1$ regions to the circle - which you might like to prove.

So, in adding a fifth point to the fourth circle, we’ll need to add four new lines.

The two lines to the adjacent points each add a single region - they don’t cross any other lines. The lines to the two opposite points each cross two lines, creating three new regions. Overall, that’s 1 + 3 + 3 + 1 new regions, taking the eight regions to 16.

Let’s go a bit more methodically this time

Going from five to six is a bit trickier ((because counting is hard)).

Let’s consider the five existing points, going anticlockwise from our new point (which I’ll imagine is at the bottom of the circle). Each new line will split the polygon into two parts, which I’ll call ‘left’ and ‘right’.

The first line, to the neighbour, crosses no lines, and adds one region.

The second line, to point 2, splits the circle so there is one point to the left and three to the right, all of which are connected - so this line adds $1 \times 3 + 1$ regions.

The third line splits the circle two on each side, so it adds $2 \times 2 + 1$ regions.

The fourth line mirrors the second, and the fifth line mirrors the first, so I might be tempted to write the number of regions added as:

$(0\\times 4 + 1) + (1 \\times 3 + 1) + (2 \\times 2 +1) + (3 \\times 1 + 1) + (4 \\times 0 + 1)=15$

… or better, the new number of regions is $5 + \sum_{i=0}^{4} i(4-i)$

But we can generalise!

Whenever we add a point to a diagram, the process is going to be identical! Each line will divide the existing points into three sets: those to the left, the one being connected, and those to the right. Every point on the left connects to every point on the right exactly once, so the number of lines cut by the new line is always the number of left points multiplied by the number of right points.

So! If we’re moving from $N-1$ points to $N$, we should be adding:

$R\_n = (N-1) + \\sum\_{i=0}^{N-2} i( (N-2) - i)$

new regions.

And we can write that explicitly!

$R\_n = (N-1) + (N-2)\\sum\_{i=0}^{N-2} i - \\sum{i=0}^{N-2} i^2$ $= (N-1) + (N-2)\\frac{(N-2)(N-1)}{2} - \\frac{ (N-2)(N-1)(2N-3)}{6}$ $= \\frac{(N-1)}{6} \\left\[ 6 + 3(N-2)^2 - (N-2)(2N-3) \\right$\] $= \\frac{(N-1)}{6} \\left\[ N^2 - 5N + 12 \\right$\]

Let’s check that with $N=6$, which we’ve already worked out: $R_n = \frac{5}{6}\left[ 36 - 30 + 12 \right] = 15$ new regions.

How about $N=7$? We’re expecting 26: $R_n=\frac{6}{6}\left[ 49 - 35 + 12\right] = 26$. Hooray!

Hang on - that’s just the new regions!

So, the number of new regions each time is $\frac{N-1}{6} \left[ N^2 - 5N + 12 \right]$, and we know when there are no points, there is one region.

So, the number of regions altogether is $R_\sum(M) = 1 + \frac{1}{6}\sum_{N=0}^{M} (N-1)(N^2 - 5N + 12)$.

Expanding that and distributing the sum:

$R_\sum(M) = 1 + \frac{1}{6} \sum_{N=0}^{M} N^3 - \sum_{N=0}^{M} N^2 + \frac{17}{6}\sum_{N=0}^{M} N - \sum_{N=0}^{M} 2$

There follows an awful lot of tedious algebra, which ends up giving $R_\sum(M) = \frac{1}{24}\left(M^4 - 6M^3 + 23M^2 - 18M + 24\right)$

Just to check, we know $R_\sum(6)$ is 31: is that $\frac{1}{24}\left( 6^4 - 6\times6^3 + 23\times 6^2 - 18\times 6 + 24 \right)$? The first two terms cancel, and the rest? It’s $\frac{6}{24} \left( 23 \times 6 - 18 + 4\right)$, or $\frac{1}{4} \times 124 = 31$, as required!

Curiously, it turns out that $R_\sum(10) = 256$, which is also a power of 2 (although half as big as it “ought” to be if it followed the doubling pattern.)


# Combinatorics: how many unique polygons can be drawn using up to p points along a circle?

I am faced with the following problem:

Let p ≥ 3 be a prime number, and mark p points at equal distance on the circumference of a circle like in the pictures below (where p = 7). We can trace polygons by choosing a certain amount of those points as vertices, and connecting them with non-intersecting straight lines.

With three parts:

a) How many different polygons can we form if we consider that a different choice of vertices leads to a different polygon?

This is straightforward: you can have polygons with three vertices, 4 vertices […] up until p vertices, and the amount of polygons you can draw of a given number of vertices k is $$p \choose k$$. Hence the answer is $${p \choose 3} + {p \choose 4} + {...} + {p \choose p-1} + {p \choose p}$$

b) How many different polygons can we form if we count all different rotations of the same polygon as a single polygon?

Well, any given polygon can be rotated up to $$p-1$$ times. Hence each polygon counted from a) is actually being counted 7 times. We adjust for this by dividing through the answer in a) by p, and get the answer as $$\frac{p \choose 3}{p} + \frac{p \choose 4}{p} + {...} + \frac{p \choose p-1}{p} + \frac{p \choose p}{p} = \frac{p \choose 3}{p} + \frac{p \choose 4}{p} + {...} + \frac{p \choose p-2}{p} + 1 + 1$$.

I think all the above makes sense, but I am struggling with the third part:

c) How many different polygons can we form if we count all isometric polygons (all rotations and reflections of the same polygon) as the same ?

And I don't know how to proceed from here. I'm guessing there has to be some pattern to the number of reflections+rotations that any polygon of k vertices has along p points. However, I've tried playing around with small examples and I can't seem to find any generalizable pattern, and I've been stumped for longer than I'd like to admit. Any help would be greatly appreciated.

• Reworded: How many necklaces and bracelets (necklaces for part b and bracelets for part c) of length $p$ with $p$ prime can be made with beads of two possible colors such that there are at least three beads of the first color used. – JMoravitz Feb 5 '20 at 19:47
• Almost exactly the same question was posted just a week ago but then deleted when I answered it. a) Does this happen to be from an ongoing contest? If so, are you aware of the contest problem policy? b) If it isn't, and I post an answer, do you promise not to delete the question? :-) – joriki Feb 5 '20 at 19:47
• @joriki it is not a contest problem. I haven't seen the other post / don't see why it was deleted. This is a problem from a university class :) – Student_514 Feb 5 '20 at 19:51

The polygons are in correspondence with the subsets of the vertices with at least $$3$$ elements. Thus, as JMoravitz noted in a comment, this can be viewed as counting binary necklaces and bracelets of length $$p$$ with at least three beads of the first colour, where the first colour signifies a vertex that’s included and the second colour signifies a vertex that isn’t included in the polygon.

For part a), there is no symmetry to take into account, so the result is just $$2^p-\binom p2-\binom p1-\binom p0$$. (Your result is correct, you just didn't use the fact that $$\sum_k\binom pk=2^k$$, the total number of subsets of the set of $$k$$ vertices.)

For part b), with rotational symmetry, you failed to properly account for the fact that the polygon that includes all vertices has only one rotational equivalent, not $$p$$. Your final result is correct, but only because you replaced $$\frac{\binom pp}p=\frac1p$$ by $$1$$. If you count correctly, you have $$2^p-\binom p2-\binom p1-\binom p0-\binom pp$$ polygons that form classes of $$p$$ rotational equivalents each, and $$\binom pp=1$$ polygon that’s in a class of its own, so the total count is

$$\frac{2^p-\binom p2-\binom p1-\binom p0-\binom pp}p+1=\frac{2^p-2}p-\frac{p+1}2\;.$$

For part c), with rotational and reflectional symmetry, it becomes easier to perform the count using Burnside’s lemma. The general result is given in the Wikipedia article linked to above. In your case, since $$p$$ is an odd prime, there are

$$\begin{eqnarray} B_2(p) &=& \frac12N_2(p)+\frac12\cdot2^{\frac{p+1}2} \\ &=& \frac12\cdot\frac1p\left(1\cdot2^p+(p-1)\cdot2^1\right)+2^{\frac{p-1}2} \\ &=& \frac{2^{p-1}-1}p+1+2^{\frac{p-1}2} \end{eqnarray}$$

binary bracelets. We need to subtract the $$1$$ bracelet with $$0$$ elements of the second colour, the $$1$$ bracelet with $$1$$ element of the second colour and the $$\frac{p-1}2$$ bracelets with $$2$$ elements of the second colour, so the number of polygons up to rotations and reflections is

$$\frac{2^{p-1}-1}p+2^{\frac{p-1}2}-\frac{p+1}2\;.$$