## Prime String

### January 10, 2017

Today’s exercise is easy to describe, but has some tricky edge cases that make it hard to implement:

Given a string of the prime numbers appended sequentially — 2357111317192…. — and an index

n, return the string of five digits beginning at indexn. For instance, the five characters starting at indexn= 50 are 03107. The first 61 characters of the prime string are shown below:0 1 2 3 4 5 6 0123456789012345678901234567890123456789012345678901234567890 2357111317192329313741434753596167717379838997101103107109113

Your task is to write a program to find the substring of the string of all primes starting at the *n*th character. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

In Python. primegen is a lazy prime generator.

Decoupling digit generation from slice selection, in Python.

A Haskell version.

This is Julia 0.5, with its new generator expressions. I didn’t find an unbounded prime generator (one could be written) so I just fake it with a sufficiently large pool of primes, which is readily available. Julia’s iteration protocol is similar to but different from that of Python, ISWIM. In particular, the value of a generator expression does not itself have state.

(Re my Julia above, a nicer way to count the total number of digits in primes below 2017.)

Here’s some JS using the new ES6 generators. This one only starts building up the string once the first required prime is reached, before that it just keep a character count for the primes seen. Uses a simple incremental sieve of Eratosthenes – not the most efficient, but does the job.

package prime.string;

import static java.lang.System.out;

import java.util.Scanner;

public class PrimeString {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

out.print(“Enter the index: “);

int index = keyboard.nextInt();

out.println();

int a = 2;

String b = “”;

while(b.length() < index+5)

{

if(a % 2 != 0 && a % 3 != 0 && a % 5 != 0 && a % 7 != 0 || (a == 2 || a == 3 || a == 5 || a == 7))

{

b += a;

}

a++;

}

System.out.println(b.substring(index,index+5));

}

}