E D R , A S I H C RSS

Prime Number Practice

No older revisions available

No older revisions available



#include <iostream>

using namespace std;

const int scope = 2000;

void SetScope(int scope[], int length);
void CalculatePrimeNumber(int scope[], int length);
void PrintPrimeNumber(int scope[], int lengh);

// this program print prime number in scope 1 to 2000
int main(void) {
	int targetNumberScope[scope + 1];

	SetScope(targetNumberScope, scope);
	CalculatePrimeNumber(targetNumberScope, scope);
	PrintPrimeNumber(targetNumberScope, scope);

	exit(EXIT_SUCCESS);
}

void SetScope(int scope[], int length) {
	for (int i = 0; i < length; i++)
		scope[i] = true;
}

void CalculatePrimeNumber(int scope[], int length) {
	for (int masterIter = 2; masterIter < length; masterIter++) {
		if (scope[masterIter]) {
			for (int i = 2, secondIter = masterIter * i; secondIter < length; secondIter = masterIter * ++i) {
				if (scope[secondIter])
					scope[secondIter] = false;
			}
		}
	}	
}

void PrintPrimeNumber(int scope[], int length) {
	for (int i = 1; i < length; i++) {
		if (scope[i])
			cout << i << " | ";
	}
}

Java 로 연습
public class PrimeNumberTest {

	static final int SCOPE = 2000;
	
	private static boolean numberPool[];
	
	private static void InitializeNumberPool() {
		numberPool = new boolean[SCOPE + 1];
		for (int i = 0; i <= SCOPE; i++)
			numberPool[i] = true;
	}
	
	private static void CalculatePrimeNumber() {
		for (int i = 2; i <= SCOPE; i++) {
			if (numberPool[i])
				for (int j = i, k = 2; j * k <= SCOPE; k++)
					numberPool[j * k] = false;
		}
	}
	
	private static void PrintResult() {
		for (int i = 1; i <= SCOPE; i++)
			if (numberPool[i])
				System.out.print(i + " -> ");
	}
	
	public static void main(String[] args) {
		InitializeNumberPool();
		CalculatePrimeNumber();
		PrintResult();
	}
}

세번째는 OOP 로 도전 예정..
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:24:02
Processing time 0.0160 sec