Last active
August 29, 2015 14:11
-
-
Save dudymas/626da955bd6caebf1d43 to your computer and use it in GitHub Desktop.
Messing with factorization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<title>Factorisation Diagrams - Jason Davies</title> | |
<style> | |
body { | |
font-family: sans-serif; | |
} | |
svg { | |
margin: 5px; | |
} | |
text { | |
font-size: 10px; | |
} | |
</style> | |
<h1>Factorisation Diagrams</h1> | |
<div id="vis"></div> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
var width = 1 << 7, | |
height = 1 << 7; | |
var svg = d3.select("#vis").selectAll("svg") | |
.data(d3.range(1, (100) + 1)) | |
.enter().append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
svg.append("text") | |
.attr("dy", "1em") | |
.text(String); | |
svg.append("g") | |
.attr("transform", "translate(" + [width / 2, height / 2] + ")") | |
.each(function(d) { | |
d3.select(this).call(diagram, primeFactors(d), width / 2); | |
}); | |
function diagram(selection, factors, size) { | |
if (factors.length) { | |
var n = factors.pop(), | |
offset = n === 4 ? 45 : n === 2 ? 0 : -90, | |
radius = n * size / (n + 2), | |
δy = n & 1 ? (radius / 2) * (1 - Math.cos(Math.PI / n)) : 0; | |
selection.selectAll("g") | |
.data(d3.range(n)) | |
.enter().append("g") | |
.attr("transform", function(d) { | |
var angle = d * 360 / n + offset; | |
return "translate(0," + δy + ")rotate(" + angle + ")translate(" + radius + ")rotate(" + -angle + ")"; | |
}) | |
.call(diagram, factors, 2 * size / (n + 2)); | |
} else selection.append("circle").attr("r", size * .9); | |
} | |
function primeFactors(n) { | |
var factors = [], | |
f; | |
while (n > 1) { | |
factors.unshift(f = factor(n)); | |
n /= f; | |
} | |
return factors; | |
} | |
function factor(n) { | |
if (n % 4 === 0) return 4; | |
for (var i = 2; i <= n / 2; i++) { | |
if (n % i === 0) return i; | |
} | |
return n; | |
} | |
</script> | |
<p>I nabbed this from <a href="http://www.jasondavies.com/">Jason Davies</a> 2012.</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment