I won't do the whole thing for you, but here is an example of a program that generates a list of factor pairs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <vector>
#include <iostream>
struct NumberPair {
NumberPair(int num1, int num2)
: n1(num1),
n2(num2)
{}
int n1;
int n2;
};
int main()
{
std::vector<NumberPair> factor_pairs;
int n;
std::cin >> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i * j == n)
factor_pairs.push_back(NumberPair(i, j));
}
}
for (int i = 0; i < factor_pairs.size(); i++)
{
std::cout << factor_pairs[i].n1 << " " << factor_pairs[i].n2 << std::endl;
}
}
|
If you haven't learned what vectors or structs are, sorry. Vectors are dynamic arrays and structs are just a way of organizing data together. You don't have to use this them solve this.
Try running this program and enter 24.
The output will be
1 2 3 4 5 6
|
2 12
3 8
4 6
6 4
8 3
12 2
|
So these are your factor pairs, as in, all of them make a product of 24.
What you then need to do is find which pair gets you the minimal absolute value of (n2 - n1).
In this case, it would be 4 and 6, and b would need to be 6 since it's the larger number.
This could be done without using an array if you keep track of the minimal difference inside the for loop itself.
One more thing I'll throw in, this doesn't involve structs or arrays:
1 2 3 4 5 6 7 8 9 10 11 12
|
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// see if i * j equals n. If it does, see if the absolute value of i - j
// is the minimum value seen so far.
// (You'll need a variable to keep track of the minimal value so far)
// If it is, make the new minimum value be abs( i - j),
// and make b = std::max(i, j)
// and make a = std::min(i, j)
}
}
|
(Heh, I guess I did end up doing most of it, but I don't mind since you at least first attempted to do it yourself).