C algorithm not working correctly.
Hello
I have made a prime number algorithm, its working very well on integers under 1 billion. At first i did not use malloc() to allocate the space nessesary for the divisors array, i was doing it directly with the int variable n. This dident work on large integers, and the program made a stackdump. Code:
#include <stdio.h> Any help is greatly appreciated. |
Quote:
My guess would be that the memory allocation is failing. You say that prime() is returning 0, but you do not have any code that verifies this. The message "Not prime" is displayed whenever prime() returns anything but 1. If memory allocation fails, it returns -1, which will lead to the same "Not prime" message being displayed as if 0 had been returned. |
It's been a while since my prior reply. What I'm going to add, I'd rather make sure it's seen and not potentially missed (because an edit would not send a "new reply" email).
Three things (that you did not ask for), but that I want to make sure you are aware of. #1) You have a memory leak. Code:
if(result == (int)result) { #2) You do not need to do the memory allocation at all. Your prime() function can simply use a single integer that you increment repeatedly. For example: Code:
int prime(int n) { If you want your program to process higher values than those, consider using unsigned int (range: [+4,294,967,295, 0]) long int (range: [+9,223,372,036,854,775,807, -9,223,372,036,854,775,808]) unsigned long int (range: [+18,446,744,073,709,551,615, 0]) Though, if you do use the greater-range variable types, I strongly encourage you to experiment with creating some alternate method of determining a prime than by your current increment-divide approach. |
also, hint: you only have to check up to the square root, for obvious reasons if you think about it.
|
Quote:
Thanks for the help, bigearsbilly and Dark_Helmet. |
Since you're using single-precision numbers (i.e. float,) your algorithm becomes unreliable for values > 8388608 (the width of the "fraction" component is 23 bits,) which could easily give you a false-positive for having a factor of 1000000007. You should use % instead of / and eliminate numbers if the result is zero (i.e. skip the floating-point.)
Kevin Barry |
All times are GMT -5. The time now is 05:38 AM. |