I want to create a program that will find the factors of a given number.
I have thought up of this concept:
The User will enter a value (say x).
The program will divide the number by 2 then 3, than 4 ... (until x/2)
The program will then publish all the values that were whole numbers.
Now I wanted help with two things:
1. How do I make the program see that whether the value is int or float?
2. How do I make the program publish the values that returned the int value?
It rounds down the number, if you aren't familiar with the standard math library I would recommend visiting http://cplusplus.com/reference/clibrary/cmath but looking at your second topic, I noticed you don't actually need that. As hamsterman correctly mentioned, you should use the modulus operator (%).
By "publish", do you mean print the values? You'll just need to add basic output to your if statement.
Yes. But say there are 5 values that give the result as 0. I don't know which values they are. But I want the program to be able to print those values in the output. Now How do I do that?
#include <iostream>
#include <string>
usingnamespace std;
//Variables
int number; //The number whose factors are to be calculated
int divider = 2; //The Divider
int factor; //Potential Factors
int factors; //Actual Factors
//Exit Variables
char x = 'N';
char h = 'N';
int main ()
{
do
{
//Asking for input:
cout << "Please enter the value whose factors you want to calculate:" << endl;
cin >> number;
cout << endl;
//Calculatin the value
do
{
factor = number % divider;
//Divider condition
do
{
if (divider < number/2)
{
divider = divider + 1;
}
}while (divider < number/2);
}
while (divider > number/2);
//Giving the factors:
cout << "The factors of " << number <<" are:" << endl;
cout <<"1" << endl;
cout << number << endl;
//Code for exiting the program.. irrelevant to the its functioning...
//Terminating the Program
return 0;
}
In giving the factors part, I have put up 1 & the number as the factors. I don't know how to do so for other factors.
You over-complicated it. You should simply loop through the numbers 1...n/2 and print the once that n can be divided by without a remainder. Those will be the factors.
1 2 3 4 5 6 7
// ... receive `n` from the user, etc.
cout << "The factors of " << n << "are:" << endl;
for (int divider = 1; divder <= n/2; divider++) {
if (n % divider == 0)
cout << divider << endl;
}
cout << n << endl;
As I said, the loop goes from 1 to n/2, increasing `divider` and for every value of `divider` it is to check if n can be divided by `divider` using the modulus operator. if it can, `divider` is indeed a factor of n so we print it. Also, n can always be divided by n so we print it as well (just like you did).