Effacer les filtres
Effacer les filtres

How to find the pair of divisors which are closest in value for a non-prime number? If prime, how to do this for the next largest non-prime?

8 vues (au cours des 30 derniers jours)
Case 1: I would like to find the largest two divsors, 'a' and 'b', of a non-prime integer, N such that N = a*b. For instance if N=24, I would like to a code that finds [a,b]=[4,6] not [a,b] = [2,12] etc.
Case 2: If N is prime, say N=11, how do I do this for the next non-prime number? so N=11->N=12 and [a,b] = [3,4].
(For context, I have a loop that generates a number of traces to be plotted where the value N is not known ahead of time. Sometimes N=3 and sometimes N=23. I'm trying to arrange the plots with subplot in a mostly 'square' arrangement that isn't just a skinny column or a skinny row. ).
  2 commentaires
David Goodmanson
David Goodmanson le 24 Avr 2021
Hi Travis,
for n=14 for example, will 2x7 (which fits the rule) be all right, or would 3x5 be better? for n = 22 would 2x11 be all right, or would 4x6 be better?
Travis Briles
Travis Briles le 24 Avr 2021
Good point. Yes I agree that for N=14-> 3x5 is better. Same for N=22 -> 4x6.

Connectez-vous pour commenter.

Réponse acceptée

Clayton Gotberg
Clayton Gotberg le 24 Avr 2021
If you're not dead-set on your method for determining the number of tiles in a subplot, how about using the square root of the integer N to decide the size of the subplot?
N = 24;
rows = floor(sqrt(N)); % sqrt(N) is ~4.89, k =4
columns = ceil(N/rows); % Makes certain there are enough columns to fit all of the tiles
With this method there may be extra tiles (for example, with N = 10 there would be 3x4 tiles with two unused) but the output should be about as square as possible.
If you want to find all divisors of a number and pick the ones that are squarest, you can try:
N = 24;
if isprime(N)
N = N+1;
possible_factors = 1:ceil(sqrt(N)); % Thanks @Peter
% https://www.mathworks.com/matlabcentral/answers/21542-find-divisors-for-a-given-number#comment_806547
factors = possible_factors(rem(N,possible_factors)==0);
[~, indexOfMin] = min(abs(factors-sqrt(N))); % Thanks @ImageAnalyst
% https://www.mathworks.com/matlabcentral/answers/152301-find-closest-value-in-array#comment_536274
square_row_value = factors(indexOfMin);
square_column_value = N/square_row_value;
  3 commentaires
Steven Lord
Steven Lord le 24 Avr 2021
The only case for positive N where both N and N+1 are prime is when N = 2.
Clayton Gotberg
Clayton Gotberg le 24 Avr 2021
There I go again! Maybe you do want to loop the check until N is definitely no longer prime.
while isprime(N)

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by