Entry Level C++ Problems: Find Prime Numbers Within a Range

Today we’re going to write a program that finds the prime numbers within the range specified by the user.

First we need to ask the user to input the range:

#include <iostream>

int main()
{

	int lowerLimit;
	int upperLimit;
	int index = 0;

	std::cout << "Type in the lower limit: ";
	std::cin >> lowerLimit;
	std::cout << std::endl;

	std::cout << "Type in the upper limit: ";
	std::cin >> upperLimit;
	std::cout << std::endl;

	return 0;
}

There are only two numbers that a prime can be divided by to return an integer: by itself and by 1. 1 is not a prime number. We’ll need to scan over the entire range to test all the numbers within it.

First loop will in this case span between lower and upper limits. We then throw in another loop inside to test how many numbers will make the current number divide into an integer (reminder is equal to 0). Everytime that is detected the index counter will increment by 1. After the inner loop stops iterating, if the index counter is equal to 2 we’ll print the number on screen since it is a prime number. Every other number will not be printed.

#include <iostream>

int main()
{

	int lowerLimit;
	int upperLimit;
	int index = 0;

	std::cout << "Type in the lower limit: ";
	std::cin >> lowerLimit;
	std::cout << std::endl;

	std::cout << "Type in the upper limit: ";
	std::cin >> upperLimit;
	std::cout << std::endl;

	for (int i = lowerLimit; i <= upperLimit; i++)
	{

		index = 0;

		for (int j = 1; j <= i; j++)
		{
			if (i % j == 0)
			{
				index++;
			}
		}

		if (index == 2)
		{
			std::cout << i << std::endl;
		}
	}

	return 0;
}

And that’s the program. Cheers!

Leave a Reply

Discover more from NMKN Studio

Subscribe now to keep reading and get access to the full archive.

Continue reading