i have a two part question for my computer programming class, the first part i already completed, i had to create a program that allows the user to enter any integer then my program will display the factors of that integer using a loop and % to get the factors.
for the second part of the question i have to display whether the number the user entered is prime or not. i need to do this by storing the factors somewhere and then create a function named isPrime and if the number the user entered has exactly 2 factors then isPrime would return: cout<< "the number you entered is prime", for any other number of factors stored it would return: cout<< "the number you entered is not prime".
here is the program to the first part (this works)
#include<iostream>
#include<cstdlib>
#include<cmath>
usingnamespace std;
int main()
{
cout << "Enter any integer: ";
int a;
cin >> a;
int i=1;
while(i<=abs(a)) //used absolute value so that it also works for negative numbers
{
if(i==1)
cout << "The factors of " << a << " are: ";
if(a%i==0) //this is how to find the factor because if it is divided by a number and it doesn't have a remainder it is a factor of the number the user entered
cout << i <<" ";
i++;
}
cout << endl;
system("PAUSE");
return 0;
}
this is the idea im working on for the second part but i cant get it to run.
#include<iostream>
#include<cstdlib>
#include<cmath>
usingnamespace std;
string isPrime(int[], int);
int main()
{
cout << "Enter any integer: ";
int a;
cin >> a;
int nums[a];
int i=1;
while(i<=abs(a))
{
if(a%i==0)
cin >> nums[i]; //is this the way to store the factors in an array for later use in the return function?
i++;
}
cout << a << "is " << isPrime(nums,a) << endl;
system("PAUSE");
return 0;
}
string isPrime(int a[], int size) //how do i set up the return function so it returns "prime" if only 2 numbers are store in int nums and "not prime" for any other amount stored in int nums?
{
if(int nums==2)
return"prime.";
elsereturn"not prime.";
}
line 19: cin is looking for user input. doens't seem to be desired here
line 31: 'nums' is not defined here and the rest of it makes no sense ('int' and '==2)' ?
lines 32 and 34: i believe those returns are char* while the function is looking for a string
I'm not sure why the question is asking for that particular design.
You're already attempting to check for prime-ness in that while loop before the isPrime function even begins. It asks to keep track of the factors but the factors are not being used except to reconfirm the while loop's test for a prime number.