Sunday, December 06, 2009

D Code

I had a little time, and started playing with primes again (something fascinating about primes).

Good chance for a little D code:

import std.stdio;

bool isPrime(uint n, uint[] curPrimes)
{
foreach(i; curPrimes)
{
if( n % i == 0 )
{
return false;
}
}
return true;
}

void main(char[][] args)
{
uint[] primes;
primes ~= 2;

uint i = 3;
while( i < 1000 )
{
if( isPrime(i, primes) )
{
primes ~= i;
}
i += 2;
}

writefln(primes.length);
writefln(1);
foreach(j; primes)
{
writefln(j);
}
}

The C++ code is very similar (except with lots more editing for HTML, with &gt; and &lt;):

#include <iostream>
#include <vector>

bool isPrime(unsigned n, const std::vector<unsigned> &curPrimes)
{
for(std::vector<unsigned>::const_iterator i = curPrimes.begin();
i != curPrimes.end(); ++i)
{
if( n % *i == 0 )
{
return false;
}
}
return true;
}

int main(int argc, char **argv)
{
std::vector<unsigned> primes;
primes.push_back(2);

unsigned i = 3;
while( i < 1000 )
{
if( isPrime(i, primes) )
{
primes.push_back(i);
}
i += 2;
}

std::cout << primes.size() << std::endl;
std::cout << 1 << std::endl;
for(std::vector<unsigned>::const_iterator i = primes.begin();
i != primes.end(); ++i)
{
std::cout << *i << std::endl;
}

return 0;
}

I've already complained about hideous iterator syntax. But I will post more on some D goodness, when it comes time to make improvements to the algorithm.

No comments: