Echo89 9 Web Developer
EDIT

Fixed - skipped ever having to use an array. Although, I'd still like to know if I was right about the stack size, and what the best way might be to keep that many elements in an array.

Prerequisites

Operating System: OS X 10.10 Yosemite (64 bit)

Question

Hi,

I've written this small program in D, as I want to teach myself more about compiled langauges, but I've encountered a small problem with the program ending because of a segmentation fault.

This program just calculates prime numbers up to ITERATIONS, and writes them to a file (and outputs them to tty). It works fine, to a point. For instance, if I set ITERATIONS to 100,000; it works just fine. If I set it to 1,000,000; it ends with a segmentation fault.

Output with 100,000:

Last login: Sun Oct 19 13:41:12 on ttys000
You have mail.
Caelans-MBP:~ Caelan$ /Users/Caelan/Dev/D/Testing/Primes ; exit;


9592 prime numbers calculated in 3.98622 seconds.
logout

[Process completed]

Output with 1,000,000:

Last login: Sun Oct 19 13:41:39 on ttys000
You have mail.
Caelans-MBP:~ Caelan$ /Users/Caelan/Dev/D/Testing/Primes ; exit;
Segmentation fault: 11
logout

[Process completed]

Now, I have a feeling that this is somethig to do with the stack size being to large, and that I would need to allocate memory. But I'm not sure, so I'd like to get confirmation beforehand.

Here is the actual code:

import std.stdio;
import std.math;
import std.datetime;
import std.file;

enum size_t ITERATIONS = 1000000;

bool divisible(real n) {
    real d;
    for(d = 3; d < floor(n / 2); d += 2) {
        if(fmod(n, d) == 0) {
            return true;
        }
    }

    return false;
}

void main() {
    StopWatch sw;
    size_t T = ITERATIONS;
    size_t C = 0;
    real n = 2;
    real[ITERATIONS] r;
    sw.start();
    r[0] = n;
    C++;
    for(n = 3; n < T; n += 2) {
        if(!divisible(n)) {
            r[C] = n;
            C++;
        }
    }

    sw.stop();
    double seconds = cast(double)sw.peek().usecs / 1000000;
    writeln("\n\n", C, " prime numbers calculated in ", seconds, " seconds.");

    real[] f;
    f.length = C;
    f = r[0..C];
    File file = File("primes.txt", "w");
    file.writeln(C, " prime numbers calculated in ", seconds, " seconds.");
    foreach(number; f) {
        file.writeln(number);
    }
    file.writeln("\n", "end");
    file.close();
}

Thanks in advance!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.