### 技术控

今日:167| 主题:57262

# [其他] Computing primes with CSS

Amrice做作 发表于 2016-9-30 15:46:45
157 1
 I've been working on a redesign of this site, so doing more CSS, finally internalizing Sass, etc. During my reading, the    nth-child pseudo-classcaught my eye. It's oddly specific, providing syntax like "p:nth-child(4n+3)" to select every fourth paragraph, starting with the third. It isn't an arbitrary expression, it has to be of the form An+B, where A and B are integers. An element is selected if it is the An+B'th child of its parent, for some value of n ≥ 0.     It struck me that this is just enough computational power to compute primes with a Sieve of Eratosthenes, so I whipped up an demonstration (see it    live here):

Primes:

1 2 3 4 ... 996 997 998 999
The code has only linear sequences of numbers. There are spans for 1 through 999, the candidate numbers. These are arranged so that the number N is the Nth child of their containing div. The CSS has nth-child styles for 2 through 32, the possible factors.   The Sieve will hide numbers that are determined not to be primes with a "display: none" rule. A first-child selector hides 1, which is typical, seems like you always have to treat 1 specially when looking for primes. The other selectors for the display:none rule select the multiples of each number in turn. "nth-child(2n+4)" will hide elements 4, 6, 8, and so on. "nth-child(3n+6)" will hide 6, 9, 12, and so on.   So CSS has two features that together are just enough to implement the Sieve. The nth-child selector accomplishes the marking of factors. The overlapped application of separate rules implements the multiple passes, one for each factor.   Of course, I didn't write this file by hand, I wrote a Python program to do it. It's pretty simple, I won't clog up this post with the whole thing. But, it was my first use of a new feature in Python 3.6: f-strings. The loop that writes the nth-child selectors looks like this:     for i in range(2, 33):     print(f"span:nth-child({i}n+{2*i}),")    The f"" string has curly-bracketed expressions in it which are evaluated in the current scope. This string in Python 3.6:     f"span:nth-child({i}n+{2*i})"    is equivalent to this in previous Pythons:     "span:nth-child({i}n+{i2})".format(i=i, i2=2*i)    It felt really natural to use this new feature, and really convenient.

zangqing 发表于 2016-10-8 16:04:02
 十分赞同楼主！

• ## 西甲意甲冠军日，段子手先嗨爆了。。。

微信号 fengkeclub [...]

• ## 深扒 | 杨幂的灵气少女感你也可以轻松get~

微信号 huazhuangbd [...]

• ## 一套西装居然拯救了一个“渣男”？

微信号 GQZHIZU “ [...]

• ## 打赌吧！穿这样进办公室，够美老板还没话说

微信号 cosmochina [...]

• ## ćĽçłťćĺżĺčŻä˝

ĺžŽäżĄĺˇ [...]

• ## 污蔑 | 澳洲名校考题涉辱华 引发留学生不满

微信号 bbnalanniao [...]

• ## 凯特王妃妹妹大婚！520秀尽恩爱！

微信号 Wedding21-S [...]

• ## 【热点】澳名校考题涉辱华，外国人眼中的另

微信号 jnwjgf2017 [...]

• ## Fendić°ĺ­Łçć°ĺé

ĺžŽäżĄĺˇ [...]

• ## 爱吃柚子的不是吃货，是护肤专家

微信号 i-EVER4ever [...]