HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Prime number generator exercise

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberprimeexercisegenerator

Problem

I have been trying to create a class that would list prime numbers forever. I know it has already been done but I think I learned some valuable principles during my trials.

This project helped me understand (to a better extent) return values, arguments for methods, simple math arithmetic and what I personally enjoyed working with was the power of the for and if/else statements.

I would appreciate any insight into improvements that would increase this code performance and/or any obvious flaws with my code structure.

```
//first the class is declared
public class startListingPrimeNumbers {

// method is created to start the prime number listing from 1 to infinity
// and beyond
public void startFromOneListingPrimeNumbers() {

// Create the primary for loop using doubles so the program will
// continue on infinitely
for (double x = 1; x > 0.000; x = x + 1.000) {

// The double c is for determining numbers that only have 2 factors
// are prime
double c = 2.000;

// I use the primeLogger to keep track of each numbers amount of
// factors it contains, to later compare this value to c to know if
// it's prime or not
double primeLogger = 0.000;

// the multiplier is used to iterate through the for loop below
double multiplier;

// this is the bread and butter, I take multiplier and iterate it
// until it is greater than x, if a remainder exists from x divided
// by multiplier then my primeLogger adds nothing to itself
// if there is no remainder then primeLogger adds one, meaning
// multiplier is a factor of x.

for (multiplier = 1.000; multiplier <= (x); multiplier = multiplier + 1.000) {
if (x % multiplier == 0) {
primeLogger = primeLogger + 1.000;
} else {
primeLogger = primeLogge

Solution

The major problem here is using imprecise floating point values. Not only does it slow the entire process (minor quibble), but it will produce incorrect results once the values pass the integral cutoff of the field width. If you truly want to allow calculations approaching infinity (or what? 24 bits?) you need to switch to BigInteger which can model "exact" integers of any size.


Okay, they probably cap out at a very, very large number...much larger than doubles, but will likely last past the life of your PC.

This issue is so critical to the correctness of the solution that I'll leave it to stand on its own and leave any other review issues for others.

Context

StackExchange Code Review Q#43668, answer score: 22

Revisions (0)

No revisions yet.