home hardware prices news articles forums photos user reviews
Go Back   Tech Support Forums - TechIMO.com > PC Hardware and Tech > Webmastering and Programming
Ask a Tech Support Question (free)!

printing prime numbers between 1 and N (C++)

Reply
Get bargains at  »  Dealighted.com
 
Thread Tools Search this Thread
Currently Active Users: 1587
Discussions: 200,982, Posts: 2,379,844, Members: 246,344
Old February 27th, 2007, 01:12 PM   Digg it!   #1 (permalink)
Senior Member
 
BattleToad's Avatar
 
Join Date: Aug 2004
Location: Virginia Beach, Va
Posts: 603
Send a message via AIM to BattleToad
printing prime numbers between 1 and N (C++)

Perhaps some of you guys who have been doing this longer than I have could help me out. Im writing a console program that reads input from a file (inputdata.txt) and write output to a file (outputdata.txt). The program gets a number from the file, and then outputs all the prime numbers from 1 to the number. My output doesnt seem to add up, the problem is my prime testing function but I cant seem to figure out where. Could someone take a peek at my code and point me in the right direction?

Code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>

using namespace std;

bool testForPrime(int);
void writeMessage(ofstream &, int);
void writePrimes(ofstream &, int);


int main()
{
	ifstream inputdata;
	ofstream outputdata;
	
	inputdata.open ("a:\\inputdata.txt");
	if (! inputdata)
	{
		cout << "ERROR -- Cannot open inputdata.txt for input" << endl;
		return 1;
	}
	
	outputdata.open ("a:\\outputdata.txt");
	if (! outputdata)
	{
		cout << "ERROR -- Cannot open outputdata.txt for output" << endl;
		return 1;
	}

	int number2Test;

	while (! inputdata.eof())
	{
		inputdata >> number2Test;
		writeMessage(outputdata, number2Test);
		for (int i = 1; i <= number2Test; i++)
		{
			testForPrime(i);
			if (testForPrime)
			{
				writePrimes(outputdata, i);
			}
		}
		outputdata << endl;
	}
}

bool testForPrime(int i)
{
	for (int j = 2; j <= i; j++)
	{
		if (i % j == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
}

void writeMessage(ofstream & outputdata, int a)
{
	outputdata << "The number is " << a << "." << " The prime numbers less than or equal to " << a << " are:" << endl;
}

void writePrimes(ofstream & outputdata, int prime)
{
	outputdata << prime << " ";
}
Output with test number of 28
Code:
The number is 28. The prime numbers less than or equal to 28 are:
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
__________________
"There are only 10 kinds of people in the world, those that can read binary, and those that cannot."
BattleToad is offline   Reply With Quote
Old February 27th, 2007, 02:22 PM     #2 (permalink)
Super F@D Folder
 
Join Date: Jun 2004
Posts: 5,083
Send a message via AIM to sr71000
Code:
bool testForPrime(int i)
{
	for (int j = 2; j <= i; j++)
	{
		if (i % j == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
}
i can see a few problems. First off...if you call j=1 your code will reach the end without returning (error 1)
two...you only make 1 test....if i%j==0 (first call j = 2) is true it returns false else it returns true. It never bothers testing for 3 or 4 or 5 or .... all the way to j! This still isn't your main error though.

Code:
	while (! inputdata.eof())
	{
		inputdata >> number2Test;
		writeMessage(outputdata, number2Test);
		for (int i = 1; i <= number2Test; i++)
		{
*************error here******************
			testForPrime(i);
			if (testForPrime)
//should be
//                     if(testForPrime(i));
***************************************
			{
				writePrimes(outputdata, i);
			}
		}
		outputdata << endl;
	}
first you make a method call to testForPrime and it returns a bool. This is never saved anywhere (just thrown away). Then you use testForPrime as a condition for an if statement. I don't even see testForPrime declared as a variable anywhere so i'm kinda surprised this code compiles!

I don't mind helping but that better not have just been your homework assignment or something i just did. lol. Did you write that code or was u'r homework to debug it?

Last edited by sr71000 : February 27th, 2007 at 02:24 PM.
sr71000 is offline   Reply With Quote
Old February 27th, 2007, 02:59 PM     #3 (permalink)
Senior Member
 
BattleToad's Avatar
 
Join Date: Aug 2004
Location: Virginia Beach, Va
Posts: 603
Send a message via AIM to BattleToad
oh no I wrote that code, its for a programming assignment that I received last night, and is due like March 24th, I usually just do most of the program while sitting in class when they are assigned, that code is what I wrote last night during my class. I'm definitely against just giving people answers, thats why whenever I need help, I always just ask to be pointed in the right direction, so that I can figure the majority of the problem out on my own, otherwise Ill never learn anything. Thanks for the help though.

oh yeah yeah, using Visual C++ Express 2005, it gives me a warning when I compile that, but it compiles, due to that warning I figured one of the problems was how I wrote that. your way makes much more sense.

Last edited by BattleToad : February 27th, 2007 at 03:02 PM.
BattleToad is offline   Reply With Quote
Old February 27th, 2007, 03:08 PM     #4 (permalink)
Super F@D Folder
 
Join Date: Jun 2004
Posts: 5,083
Send a message via AIM to sr71000
i gave you the bottom one cus it was a minor bug...i take it you're new to programming. Those kinds of mistakes are common while you're learning . The test for prime method you should have a little more fun figuring it out . Sit down and trace through it for each value of j. You'll see what you're doing wrong in no time!
sr71000 is offline   Reply With Quote
Old February 27th, 2007, 03:23 PM     #5 (permalink)
SoMuchAnime-SoLittleTime
 
EXreaction's Avatar
 
Join Date: Aug 2003
Location: Plymouth, WI
Posts: 14,984
Blog Entries: 1
Send a message via MSN to EXreaction
Well, I would do something like this for the code...

Code:
int num = ; //this would be the number coming in
bool prime = true;
list // I don't remember how to declare an array in C++ anymore, but this needs to be an array :S

for (int i = 1; i <= num; i++)
{
    prime = true;
    for (int j = 1; j <= i; j++)
    {
        if (i%j != 0) // do mod math here to find the remainder, I have done any C++ in a long time or used % but I think it returns 0 if there is no remainder...
        {
            prime = false;
        }
    }

    if (prime == true)
    {
       list[] = i;
    }
}

list // should be the list of prime #'s...
Don't know how well it would work. I haven't done anything in C++ for a long time. But I do quite a bit in php, which is very close to C++.
__________________
My photography: Flickr

Lithium Studios - phpBB3, PHP, and Web Development

Last edited by EXreaction : February 27th, 2007 at 03:26 PM.
EXreaction is offline   Reply With Quote
Old February 27th, 2007, 03:44 PM     #6 (permalink)
Real gangstas sip on Yacc
 
jkrohn's Avatar
 
Join Date: Oct 2001
Location: Suckas-ville
Posts: 4,552
Send a message via ICQ to jkrohn Send a message via AIM to jkrohn Send a message via Yahoo to jkrohn
An array needs to be declared as a fixed sized so that it can be allocated onto memory.

As a result list[] = 1 is not a valid operation.

He doesn't need to store them anyway, just write them to the file as he finds them.

Jkrohn
__________________
Signatures blow hard
If your signature contains an ad of any kind, congratulations, you're on my ignore list.
jkrohn is offline   Reply With Quote
Old February 27th, 2007, 03:47 PM     #7 (permalink)
SoMuchAnime-SoLittleTime
 
EXreaction's Avatar
 
Join Date: Aug 2003
Location: Plymouth, WI
Posts: 14,984
Blog Entries: 1
Send a message via MSN to EXreaction
Quote:
Originally Posted by jkrohn View Post
An array needs to be declared as a fixed sized so that it can be allocated onto memory.

As a result list[] = 1 is not a valid operation.

He doesn't need to store them anyway, just write them to the file as he finds them.

Jkrohn

I see. Well, you could declare the array as a length of the num coming in...
(sorry, php doesn't have any limitation like that, you can add on to the length whenever you want and I thought it was the same for C++)

Ya, instead of putting them in the list you could just write it to the file there.
EXreaction is offline   Reply With Quote
Old February 27th, 2007, 03:51 PM     #8 (permalink)
Real gangstas sip on Yacc
 
jkrohn's Avatar
 
Join Date: Oct 2001
Location: Suckas-ville
Posts: 4,552
Send a message via ICQ to jkrohn Send a message via AIM to jkrohn Send a message via Yahoo to jkrohn
Quote:
sorry, php doesn't have any limitation like that, you can add on to the length whenever you want and I thought it was the same for C++

That is because php doesn't use actual arrays, rather ordered maps. This comes with a more expensive lookup and insert, but it is easier to use and easier to learn I guess.

Jkrohn
jkrohn is offline   Reply With Quote
Old February 27th, 2007, 03:58 PM     #9 (permalink)
SoMuchAnime-SoLittleTime
 
EXreaction's Avatar
 
Join Date: Aug 2003
Location: Plymouth, WI
Posts: 14,984
Blog Entries: 1
Send a message via MSN to EXreaction
I see.
EXreaction is offline   Reply With Quote
Old February 27th, 2007, 03:59 PM     #10 (permalink)
Super F@D Folder
 
Join Date: Jun 2004
Posts: 5,083
Send a message via AIM to sr71000
actually his code is nearly perfect. all he has to do is remove the else return true and tack it on after the for loop. No need for a bool to check conditions. also...as soon as you hit your first i that is a factor of j you should immediately return false (no reason to keep testing for more factors if we already know it's false....it's wasted cycles)
sr71000 is offline   Reply With Quote
Reply
Thread Tools Search this Thread
Search this Thread:

Advanced Search

Similar Threads
Thread Thread Starter Forum Replies Last Post
Prime 95 crashes ?? silvest Applications and Operating Systems 6 March 18th, 2005 10:32 PM
prime voltages italiamodena575 Technical Support 2 December 20th, 2004 01:57 AM
optimus prime? butch81385 IMO Community 6 April 1st, 2004 07:48 PM
What is Prime 95 good for? twistedbrntucker General Tech Discussion 3 July 13th, 2003 09:27 PM


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Most Active Discussions
Is It Just Me? (3063)
Charges against non-tippers dropped.. (20)
Health Care Rationing (10)
Delete an OS (16)
Nvidia GTX 260 problem (9)
Laptop with wireless problem. (12)
Wireless Televisions. (12)
CPU fan stops spinning randomly (11)
windows vista security holes (18)
Regular Build (11)
Point and Shoot Camera Suggestions. (7)
windows 7 problem (7)
Internet Lost (5)
Multiple Restarts Required at Boot (5)
Recent Discussions
updating BIOS via winflash, claims fi.. (1)
New Server Configuration Suggestions (0)
Desktop Calendar Application (0)
cheap gaming laptop? (12)
Unallocated Space (2)
help me pls laptop just stopped worki.. (1)
C# + LINQ Help (7)
windows vista security holes (18)
[F@H SPAM 11/16/09] ! 1/2 months to r.. (38)
Nvidia GTX 260 problem (9)
Dynex DX E-402 (3)
EVGA 9800 gtx help with finding a goo.. (12)
Multiple Restarts Required at Boot (5)
Point and Shoot Camera Suggestions. (7)
Delete an OS (16)
cell phone won't work (0)
Is the PSU I received dead? (15)
Can't open Word (12)
Steam ID's, Gamertags etc... (4)
Games, Cables, PCI cards, and more fo.. (6)
Dept. of HS: NSA 'Helped' Develop Vis.. (17)
Linksys WMP54GS wireless card problem.. (5)
Help getting around port 80 for camer.. (5)
Skillsoft Network+ Study Software Que.. (10)
Browsers wont load websites (3)


All times are GMT -4. The time now is 02:35 AM.
TechIMO Copyright 2009 All Enthusiast, Inc.



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