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

Prime number finder

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

Problem

There's another exercise from Thinking in C++.

This time it asks this:


Write a program that uses two nested for loops and the
modulus operator (%) to detect and print prime numbers
(integral numbers that are not evenly divisible by any
other numbers except for themselves and 1).

And this is what I think:

// finds all prime numbers between 2 and a number given in input.
#include 
using namespace std;

int main(int argc, char* argv[]) {
    cout > n;

    int i, j;
    bool flag = true;
    for(i = 2; i <= n; i++) {
        for(j = 2; j <= i; j++) {
            if((i % j) == 0) {
                if(i == j)
                    flag = true;
                else {
                    flag = false;
                    break;
                }
            }
        }

        if(flag)
            cout << "Prime: " << i << endl;
    }
}


It works perfectly, but I'd know what do you think about. Thanks for the feedback!

Solution

Forgive me, I'm a C# developer, I like descriptive terms :)

As Alexandre mentioned, the sqrt is key to minimize computations. Great heuristic. Another heuristic you can use is every other number will not be prime, as it will be divisible by 2. Then to expand on this heuristic, you can say that no odd numbers are divisible by even numbers and therefore may skip every other number as your divisible test number.

for(int mightBePrime = 3; mightBePrime <= upperLimitToCheck; mightBePrime += 2)
{
  bool foundAPrime = true;
  for(int divisorToCheckPrime = 3; divisorToCheckPrime * divisorToCheckPrime <= mightBePrime ; divisorToCheckPrime += 2)
  {
    if(mightBePrime % divisorToCheckPrime == 0)
    {
      foundAPrime = false;
      break;
    }
  }
}

Code Snippets

for(int mightBePrime = 3; mightBePrime <= upperLimitToCheck; mightBePrime += 2)
{
  bool foundAPrime = true;
  for(int divisorToCheckPrime = 3; divisorToCheckPrime * divisorToCheckPrime <= mightBePrime ; divisorToCheckPrime += 2)
  {
    if(mightBePrime % divisorToCheckPrime == 0)
    {
      foundAPrime = false;
      break;
    }
  }
}

Context

StackExchange Code Review Q#4043, answer score: 5

Revisions (0)

No revisions yet.