How to resolve the algorithm Prime conspiracy step by step in the Elixir programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Prime conspiracy step by step in the Elixir programming language

Table of Contents

Problem Statement

A recent discovery, quoted from   Quantamagazine   (March 13, 2016): and

The task is to check this assertion, modulo 10. Lets call    i -> j   a transition if    i   is the last decimal digit of a prime, and    j   the last decimal digit of the following prime.

Considering the first one million primes.   Count, for any pair of successive primes, the number of transitions    i -> j   and print them along with their relative frequency, sorted by    i . You can see that, for a given    i ,   frequencies are not evenly distributed.

(Modulo 10),   primes whose last digit is   9   "prefer"   the digit   1   to the digit   9,   as its following prime.

Do the same for one hundred million primes.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Prime conspiracy step by step in the Elixir programming language

Source code in the elixir programming language

defmodule Prime do
  def conspiracy(m) do
    IO.puts "#{m} first primes. Transitions prime % 10 → next-prime % 10."
    Enum.map(prime(m), &rem(&1, 10))
    |> Enum.chunk(2,1)
    |> Enum.reduce(Map.new, fn [a,b],acc -> Map.update(acc, {a,b}, 1, &(&1+1)) end)
    |> Enum.sort
    |> Enum.each(fn {{a,b},v} ->
         sv = to_string(v) |> String.rjust(10)
         sf = Float.to_string(100.0*v/m, [decimals: 4])
         IO.puts "#{a}#{b} count:#{sv} frequency:#{sf} %"
       end)
  end
  
  def prime(n) do
    max = n * :math.log(n * :math.log(n)) |> trunc      # from Rosser's theorem
    Enum.to_list(2..max)
    |> prime(:math.sqrt(max), [])
    |> Enum.take(n)
  end
  defp prime([h|t], limit, result) when h>limit, do: Enum.reverse(result, [h|t])
  defp prime([h|t], limit, result) do
    prime((for x <- t, rem(x,h)>0, do: x), limit, [h|result])
  end
end

Prime.conspiracy(1000000)


  

You may also check:How to resolve the algorithm Sort a list of object identifiers step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Hostname step by step in the Vim Script programming language
You may also check:How to resolve the algorithm Loops/While step by step in the Cowgol programming language
You may also check:How to resolve the algorithm Loops/Continue step by step in the Vala programming language
You may also check:How to resolve the algorithm Dynamic variable names step by step in the Phix programming language