I'm trying to write a program that will find all the factors and primes for a range of numbers. I have the inner loop working but I am having trouble writing the outer loop that will output the range of numbers instead of just finding the factors for one number. Any help would be appreciated.
So if the user inputs 2 for the starting number and 6 for the ending number the output would look like this:
The factors of 2 are: [] It is prime!
The factors of 3 are: [] It is prime!
The factors of 4 are: [2 ]
The factors of 5 are: [] It is prime!
The factors of 6 are: [2 3 ]
Right now my code will output just the beginning number factors. So if six is the beginning number the output will be:
FACTORS AND PRIMES PROGRAM
Finding factors and primes between
This program will find factors and primes.
Enter a starting number: 6
Enter a ending number: 6
Finding factors and primes between 6 and 6
The factors of 6 are: [2 3 ]
I'm trying to write a loop that will print the factors from the beginning number to the ending number. So if the inputs are 2,6 it will output the following:
FACTORS AND PRIMES PROGRAM
Finding factors and primes between
This program will find factors and primes.
Enter a starting number: 2
Enter a ending number: 6
Finding factors and primes between 2 and 6
The factors of 2 are: [] It is prime!
The factors of 3 are: [] It is prime!
The factors of 4 are: [2 ]
The factors of 5 are: [] It is prime!
The factors of 6 are: [2 3 ]
So I think I have figured out the outer loop part. However, now I am running into an issue with the primes. For some reason it will not continue to print "It is prime!"
#include <iostream>
usingnamespace std;
int main()
{
//Heading
cout << "FACTORS AND PRIMES PROGRAM" << endl;
cout << "Finding factors and primes between" << endl;
cout << "This program will find factors and primes." << endl;
//Request inputs
int n1;
int n2;
int factor = 0;
cout << "Enter a starting number: ";
cin >> n1;
cout << "Enter a ending number: ";
cin >> n2;
cout << "Finding factors and primes between " << n1 << " and " << n2 << endl;
//Outer Loop
int n;
n = n1;
while (n <= n2)
{
cout << "The factors of " << n << " are: [";
//Inner Loop
for(int i = 2; i < n ; i++)
{
//Factor Output
if(n % i == 0)
{
cout << i << " ";
factor++;
}
}
cout << "]";
//Prime Output
if (factor == 0)
{
cout << " It is prime!";
}
cout << "\n";
n++;
}
return 0;
}
If the input is 2, 6 it will output the following without stating 5 "is prime" :
FACTORS AND PRIMES PROGRAM
Finding factors and primes between
This program will find factors and primes.
Enter a starting number: 2
Enter a ending number: 6
Finding factors and primes between 2 and 6
The factors of 2 are: [] It is prime!
The factors of 3 are: [] It is prime!
The factors of 4 are: [2 ]
The factors of 5 are: []
The factors of 6 are: [2 3 ]