Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to find the 2 whole factors of an int that are closest together?

Tags:

c

function

int

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.

like image 872
Pyraminx Avatar asked Feb 04 '15 18:02

Pyraminx


People also ask

How do you find two closest factors of a number?

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.

What is the formula for finding factors of a number?

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)

How do you find the factors of a number using prime factorization?

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.


1 Answers

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.

like image 168
David Sherron Avatar answered Oct 05 '22 23:10

David Sherron