Saturday, April 30, 2022

Visualising prime distributions with JavaFX

Let $n \in \mathbb{N}$ be a natural number greater then zero $n > 0$. Then by the fundamental theorem of arithmetic $n$ is associated to a multiset of prime factors. By the relative multiplicities of this multiset, this number is always associated to a prime distribution. We can display these prime distributions using JavaFX.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.scene.chart.*;
import org.apache.commons.collections4.multiset.HashMultiSet;
import org.apache.commons.math3.primes.Primes;
import java.util.ArrayList;
import java.util.HashMap;

public class PrimeDistributionChart extends  Application {
    public HashMap primeDistribution(int n) {
        var factors = new HashMultiSet(Primes.primeFactors(n));
        double bigomega = (double) factors.size();
        var rval = new HashMap();

        for(var i : factors.entrySet()) {
            rval.put(i.getElement(), ((double) i.getCount()) / bigomega);
        }

        return rval;
    }

    public void start(Stage primaryStage) throws Exception {
        // this is the number to be factorised
        var initialNumber = 360;
       
        // create the prime distribution 
        var dist = primeDistribution(initialNumber);
        var dataCollection = new ArrayList();
        for(var i : dist.entrySet()) {
            var keyString = i.getKey().toString();
            var data = new PieChart.Data(keyString, i.getValue());
            dataCollection.add(data);
        }

        // make the prime distribution into a pie chart
        ObservableList pieChartData =
                FXCollections.observableArrayList(dataCollection);
        var chart = new PieChart(pieChartData);

        // put the pie chart in a stackpane
        var group = new StackPane();
        group.getChildren().add(chart);

        // set up the scene
        var scene = new Scene(group, 500,450);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Prime distribution");
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

Here is an example of the prime distribution of three hundred and sixty: You can easily change this program to display the prime distribution of any non zero natural number.

No comments:

Post a Comment