Raised This Month: $51 Target: $400
 12% 

[resolved][C++] A little prime number program.


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
stupok
Veteran Member
Join Date: Feb 2006
Old 04-06-2007 , 20:30   [resolved][C++] A little prime number program.
Reply With Quote #1

I'm just starting to learn about C++ and I converted a little program from Actionscript to C++. It's supposed to find prime numbers. The Actionscript version works perfectly, but the C++ one does not behave...

Here it is: http://www.ampaste.net/8057

Here's the Actionscript version, if you want to compare the two: http://www.ampaste.net/8058

The output of the C++ program:
Code:
 How many prime numbers shall I find?
5

 I will now find 5 prime numbers!


 x % primes[0] = 3 % 2

 Prime number: 3

 x % primes[1] = 5 % 3
 x % primes[0] = 5 % 2

 Prime number: 5

 x % primes[2] = 7 % 5
 x % primes[1] = 7 % 3
 x % primes[0] = 7 % 2

 Prime number: 7

 x % primes[3] = 9 % 7
 x % primes[2] = 9 % 5
 DEBUG: x = 11 , cycles = 0 , y = 5
 x % primes[5] = 11 % 4204784
 x % primes[4] = 11 % 29576745
 x % primes[3] = 11 % 7
 x % primes[2] = 11 % 5
 x % primes[1] = 11 % 3
 2
 3
 5
 7
 The program is over!
primes[5] should be primes[3]
I don't know how y reaches 5, because the Actionscript version only lets y to reach 3.

I'd love to see any ways I could improve my code and any advice to solve my problem. If you have a site that you found particularly useful or want to suggest one to help me learn more about C++, go for it.

Thanks for your time!

Last edited by stupok; 04-07-2007 at 00:43.
stupok is offline
stupok
Veteran Member
Join Date: Feb 2006
Old 04-07-2007 , 00:42   Re: [C++] A little prime number program.
Reply With Quote #2

Well I did some more investigating and it turns out that when the array was declared it already had funky values in it. I thought the array would be empty, or all of its values would be 0. I just set all the values to zero before executing all the prime number jazz and it works perfectly!

It's cool to see how much faster C++ works than Actionscript. I found 10,000 prime numbers in mere seconds, faster than Actionscript could find 1,000.
stupok is offline
BAILOPAN
Join Date: Jan 2004
Old 04-07-2007 , 01:34   Re: [resolved][C++] A little prime number program.
Reply With Quote #3

A quick note:
Code:
int primes[number_of_primes+1];

Is not valid C++. It's valid C, but only on the latest compilers. The fact that you can do that and not get an error means you used G++, which has a non-standard modification.

Looks like a good exercise otherwise ;)
__________________
egg
BAILOPAN is offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 18:29.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode