c++ project help..

Status
Not open for further replies.
ok I kinda need some help, I started a c++ course and I need a to make a program with the following
Requirements

*************************************************
Create a program that lists all of prime numbers. Prime Numbers are whole numbers that are only divisible by themselves and 1 (not divisible by any other whole numbers).

Have the program accept input from the user, asking for the upper limit for the list of prime numbers.

That you use the iostream preprocessor directive (for I/O) to get input from the user.

Your program uses a while loop to continue looping until it reaches the inputted value entered by the user.

An if statement is used to print only the numbers which are prime numbers and to then print them to the screen followed by the statement " is a prime number"

The modulus (%) operator is used in the calculation to determine if a number is a prime number.

You declare all of your variables prior to their use.

Program should run without errors that cause it to crash.

Your program contains comments and is properly indented
*************************************************

now I dont want a fully writen program here, I just would like some help, hints tips ideas on how to do it. FYI I've only worked with c++ for like 5hours in my life so be simple with me....

thanks in advance...
:D :D :D
 

BiggyShake

Ars Tribunus Militum
1,746
i remember doing something like that.

easy

say your upper limit is 100
you will need a loop within a loop (i think, there may be a better way to do it). the outer (or first loop) will have the current number you want to check (from 1-100) and the inner loop will check to see if it is divisible by anything. this is where you use the mod (%)operator. you want to start your checking at two and move up each time through the inner loop. anytime you find that it is divisible you should have it immediately break out of the inner loop and start on the next value of the outer loop. if it makes it all the way through the inner loop, you want to display the current value of the outer loop.

does that make sense?
 
I think I'm fucked....like i said I JUSt started this so I know nothing, and I cant figuer out how to make the number entered somehow make the list of primes less then it show on the screen.... humm I wonder.... its is what I have so far... it doesnt work though its a start...

#include <iostream.h>

int main (void)
{
// Delaration of variables
int num1;

cout << "enter a number" << endl;

cin >> num1;


{
if (num1 >> )//is greater then list of primes? and where do I put my prime list???
cout << primelist << " is a prime number" << endl: //how do I loop it????

}
return 0; // indicate that program ended successfully
}


like i said verrry simple ....
:confused: :confused:
 

DrPizza

Well-known member
93,870
code:<HR>
Code:
#include <iostream>
#include <vector>
#include <cmath> // needed for sqrt<P>using namespace std;<P>class PrimeList // a slightly optimized list of prime numbers.  It can check if a number it's checked before is prime in the amount of time it takes to look through a list
{				// and for numbers it doesn't do, it'll check for divisibility by the primes it knows, and then by odd numbers up to sqrt of the number it's checking
public:			// It'll check the first 10,000,000 integers in about a third the time it'd take to check each number's divisibility by every odd number >= 3
	PrimeList();
	PrimeList(int limit);
	~PrimeList() {};
	int calcList(int limit);
	int printList(int limit); // print first _limit_ characters.
	int getSize() { return (int)primes.size(); }
	int getMaxSize() { return (int)primes.max_size(); }
	int getLargestNonPrime() { return largestNonPrime; }
	bool isPrime(const int toCheck);
	
	friend ostream& operator<<(ostream& theStream, PrimeList& theList);
	
	const int operator[] (const int offset)
	{
		if(offset < (int)primes.size())
		{
			return primes[offset];
		}
		else
		{
			return 0;
		}
	}<P>protected:
	vector<int> primes;
	int largestNonPrime;
};<P>PrimeList::PrimeList()
{
	largestNonPrime = 4;
	primes.push_back(2);
	primes.push_back(3);
}<P>PrimeList::PrimeList(int limit)
{
	largestNonPrime = 4;
	primes.push_back(2);
	primes.push_back(3);
	calcList(limit);
}<P>bool PrimeList::isPrime(const int numberToCheck)
{
	if(2 > numberToCheck)
	{
		return false;
	}
	else if(2 == numberToCheck)
	{
		return true;
	}
	else if(0 == numberToCheck % 2)
	{
		return false;
	}
	// first check against the list we already have
	int i = 0;
	int numPrimes = (int)primes.size();
	int limit = int(sqrt(numberToCheck) + 1); // just need to check divisibility by primes from 3 to sqrt(numberToCheck) + 1.
	for(i; i < numPrimes; i++)
	{
		if(numberToCheck == primes[i])
		{
			return true;
		}
		if(0 == numberToCheck % primes[i])
		{
			return false;
		}
		if(limit < primes[i]) // We've checked everything less than sqrt(numberToCheck) + 1, but haven't returned yet.  So let's return true
		{
			return true;
		}
	}
	if(largestNonPrime >= numberToCheck)
	{
		return false;
	}
	// the following code only gets used when primes is incomplete, i.e. we haven't searched all the preceding numbers.
	int divisor = primes[i - 1];
	while(limit > divisor)
	{
		if(0 == numberToCheck % divisor)
		{
			return false;
		}
		divisor += 2;
	}
	return true;
}<P>int PrimeList::calcList(int limit)
{
	int i = 0;
	if(largestNonPrime >= limit) // we've already gone this far, so there's nothing to do.
	{
		return 0;
	}
	for(i = largestNonPrime; i <= limit; i++)
	{
		if(isPrime(i))
		{
			primes.push_back(i); // add it to the list of primes
		}
		else
		{
			largestNonPrime = i; // or update our largest non-prime
		}
		if(0 == i % 100000)
		{
			cerr << "Done " << 100 * ((double)i/(double)limit) << "% of " << limit << " numbers." << endl;
		}
	}
	return 0;
}<P>int PrimeList::printList(int limit)
{
	calcList(limit);
	int i = 0;
	for(i; i < (int)primes.size(); i++)
	{
		if(primes[i] > limit)
		{
			break;
		}
		cout << primes[i] << " ";
	}
	cout << endl;
	return 0;
}<P>ostream& operator<<(ostream& theStream, PrimeList& theList)
{
	int i = 0;
	for(i; i < (int)theList.primes.size(); i++)
	{
		theStream << theList.primes[i] << " ";
	}
	return theStream;
}<P>int main(int argc, char* argv[])
{
	PrimeList myPrimes(10000); // make a PrimeList and get all primes in the first 10,000 numbers.
	int input;
	cout << "Enter a number: ";
	cin >> input;
	myPrimes.printList(input);
//	cout << "myPrimes has " << myPrimes.getSize() << " prime numbers in it." << endl;
//	cout << "Here they all are:\n" << myPrimes << endl;
//	cout << "Calculating primes within the first 100,000 numbers..." << endl;
//	cout << "There are " << myPrimes.getSize() << " prime numbers between 0 and " << myPrimes.getLargestNonPrime() << "." << endl;
//	cout << myPrimes << endl;
	cout << "24 is " << (myPrimes.isPrime(24) ? "" : "not ") << "prime." << endl;
	return 0;
}
Hand that in and tell the teacher to go hang themself.
 

DrPizza

Well-known member
93,870
Well, the important bit is this:

code:<HR>
Code:
#include <iostream>
#include <cmath>
using namespace std;<P>bool isPrime(const int numberToCheck)
{
	if(2 > numberToCheck)
	{
		return false;
	}
	else if(2 == numberToCheck)
	{
		return true;
	}
	else if(0 == numberToCheck % 2)
	{
		return false;
	}
	int divisor = 3;
	int limit = int(sqrt(numberToCheck) + 1);
	while(limit > divisor)
	{
		if(0 == numberToCheck % divisor)
		{
			return false;
		}
		divisor += 2;
	}
	return true;
}<P>int main(int argc, char* argv[])
{
	int input;
	cout << "Enter a number: ";
	cin >> input;
	int i;
	for(i = 1; i <= input; i++)
	{
		if(isPrime(i))
		{
			cout << i << " is a prime number." << endl;
		}
	}
	
	return 0;
}

That's the basic "is this number prime?" program. Mine was sped up (actually rather a lot) by checking for divisibility by primes, not mere odd numbers. I wanted to protect the list of numbers (because it'll not work if things can add to that list willy nilly) so I stuck it into a class, with some methods to access it, but it doesn't permit direct access of the list of primes.

There aren't many comments. But in truth, it doesn't really need any. It's easy to read code. :)
 

hanser

Ars Legatus Legionis
43,853
Subscriptor++
code:<HR>
Code:
#include <iostream.h><P>bool ifPrime(int x);<P>void main()
{
	int bound, x = 0, i;
	bool tf;<P>	cout << "What is the upper boundary: ";
	cin >> bound;
	i = 2;
	x = 3;
	while(x <= bound)
	{
		tf = ifPrime(x);
		if(tf == true)
			cout << x << endl;
		x++;
	}
}<P>bool ifPrime(int x)
{
	for(int i = 2; i <= (x - 1); i++)
	{
		if(x % i == 0)
		{
			return false;
		}
	}
	return true;
}


. . .Or you could use the above. It works just as well as PeterB's ;) The teacher might even believe that you wrote it :D.
 
BiggyShake got the basic method of doing it. Given that your assignement says you have to use modulo, it's probably how you should do it. There is a faster method however, similar to what PeterB wrote (I think it's called ******** sieve (not sure of the ********). Anyway this is the algorithm:
-start with a large integer table of the numbers, in order (say, 10 000 000 ints 1, 2, 3, 4....)
-from the index 2 in your table, for every index:
--- if it doesn't contain 0
------ print its content
------ put all the indexes which are multiples of its content to 0 (easy to do by adding the number to a counter over and over until you get to your limit)

You end up with one of the quickest ways to find primes (the small ones at least). The only downside is that its memory hungry. (To find primes from on to a million, you need about 4 megs of ram. This can be optimised of course...).
 
If you want to check up to large numbers, then doing a sieve is not a good way of doing it.

An int takes 4 bytes. You need a flag for each int to mark it as prime or not. If you were cunning with bitfields, you could do that. But without extra trickery, you're looking at 5 bytes per number.

If you want to test 10,000,000 numbers then you're looking at an array of 50,000,000 bytes. That's a lot of memory.

My program isn't the most memory efficient one I could write, I'm sure, but it still used considerably less than 50 Mbytes when testing the first 10,000,000 integers for primeness.

The second program, whilst slower, is much lighter on the memory, because it has no memory; it doesn't save any previous calculations.
 

hanser

Ars Legatus Legionis
43,853
Subscriptor++
Hanser,
you only have to check up the square root of the number plus one. ;)

I actually considered doing it using part of Fermat's theorum, but that's not accurate. I figured that hazecat wouldn't think of doing it any other way other than brute force (my way, not yours), and his teacher would know that he wouldn't think of doing it any other way. Besides, modulus needed to be used. (not sqrt from math.h) Hello? did you read the description? :D
 

MarcusAurelius

Ars Scholae Palatinae
611
I actually considered doing it using part of Fermat's theorum, but that's not accurate. I figured that hazecat wouldn't think of doing it any other way other than brute force (my way, not yours), and his teacher would know that he wouldn't think of doing it any other way. Besides, modulus needed to be used. (not sqrt from math.h) Hello? did you read the description?

You still have to use modulus...i was just trying to point out that your way was fucking dumb and inefficient.
 
hehehe looks like this is turning bad :rolleyes:

I doubt you have to take hardcore scalability into account, so the easiest method to use is the Sieve of Eratosthenes.
Thanks for the name, that's what I was thinking of. I remembered it having some funky name, but couldn't quite remember what it was.

hanser: You don't need to use sqrt from math.h.
x <= sqrt(y) can be rewritten as x*x <= y (for x and y >= 0) which only involves a multiplication and is MUCH faster.
 

hanser

Ars Legatus Legionis
43,853
Subscriptor++
PeterB-

Seeing as I wrote the above eariler on in the day (2 min. after I woke up ;)) You'll have to disregard what I wrote. I have a program that I wrote a while ago, and I only went up to the square root (+1).

To give you an idea of how off I was (cloudy minded), I'm not in algebra II anymore. I'm in Trig. That's what I get I guess for being half in the bag while foruming. :rolleyes:
 
Status
Not open for further replies.