Prime number program

I am trying to translate my prime number program I wrote in Lua into C++.
I am doing this because I believe it will help me learn C++, and also because I think that it will be faster.

I am an expert Lua programmer, so my program is somewhat complicated for efficiency. the program will calculate all prime numbers that it can up to a certain number, then print some output.

here is the Lua program:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
local g=1e6--goal: 1*10^6
local next=next--localize function
local k={2}--known primes
local c=1
local r=4

local s=os.clock()--start time
for n=3,g,2 do
	local p=true--n is prime by default
	for i,q in next,k do
		if n%q==0 then
			p=false
			break
		elseif i>c then
			if n>r then
				r=q^2
				c=i
			else
				break
			end
		end
	end
	if p then
		k[#k+1]=n--add n to the table
	end
end
local e=os.clock()--completion time
print(#k.." in "..(e-s).."s @ "..math.floor(#k/(e-s)).."/s. Ratio:"..(g/#k)) 

Lua output:
78498 in 1.1s @ 71361/s. Ratio:12.739178068231

C++ code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Primes.cpp : main project file.

#include "stdafx.h"
#include "Form1.h"
#include "math.h"
#include <vector>

using namespace Primes;
using namespace std;

vector<int> k;
vector<int>::iterator q;
//k.push_back(2);
int r=0;

bool test(int g)
{
	r=sqrt((float) g);
	bool p;
	int n;
	for (n=3;n<g;n+=2){
		p=true;
		for (q=k.begin();q<k.end();q++){
			if (n%*q==0){p=false;break;}
			else if (pow((float) *q,2)>n){break;}
		}
		if (p){
			k.push_back(n);
		}
	}
	return p;
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
	Application::EnableVisualStyles();
	Application::SetCompatibleTextRenderingDefault(false);
	Application::Run(gcnew Form1());

	if (test(100)){return 0;}
	else{return 1;}

	return 0;
}
Last edited on
Easiest is put using namespace std; at line 7 (or 9 if you want).

Otherwise, at least the vectors need std::vector<unsigned int>.
ah, thanks :)
I've been working on it for a while, but what you suggested changed most of the output.

I've updated the main post to match the current program & output.
I figured it out myself.
Topic archived. No new replies allowed.