I'm a beginner still learning to us C and I don't know how to find the factors of an int that are the closest to each other.
For example, if the input was the number 6, the output would be [2,3]. If the input was 24, then the output would be [4,6].
Is there a way to do this? Any help would be appreciated.
Basically, you know that in any pair of factors, the lowest factor must be less than or equal to the square root. So if you start at the integer equal to or less than the square root of your input, and count down, the first factor you find will be the smaller of the pair of closest factors.
The formula for the total number of factors for a given number is given by; Total Number of Factors for N = (a+1) (b+1) (c+1)
Let N is the number whose number of factors is to be calculated and its prime factorization is N = αa × βb × γc × δd × …, where α, β, γ, δ, … are prime numbers and a, b, c, d, … positive integers. Now, the factors of αa are 1, α1, α2, α3, … αa.
The algorithm to do this is simple; take the square root of your number as an integer (you want to truncate, not round). Test if that value is a factor of your input; if so, your input divided by that number are your answer. Otherwise, subtract 1 from your previous value and try again.
In code (the array literal is the wrong syntax, but the theory is correct):
//this code assumes that your input is > 0, will not work otherwise
function int[] getClosestFactors(int input) {
int testNum = (int)sqrt(input);
while (input % testNum != 0) {
testNum--;
}
return {testNum, input / testNum};
}
Basically, you know that in any pair of factors, the lowest factor must be less than or equal to the square root. So if you start at the integer equal to or less than the square root of your input, and count down, the first factor you find will be the smaller of the pair of closest factors. This terminates for all integers > 0 because you will eventually reach 1, which is a factor of all other numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With