Expressing an even number in powers of 2 and a multiple of an odd number.
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
rihan jericho
le 13 Fév 2019
Commenté : rihan jericho
le 13 Fév 2019
for example, i have a number 52.
52= (2^2)*13. where 13 is odd and 4 is the power of 2. i mean, i want to express a number a=(2^r)*d, where d is odd. as soon as, for any number d becomes odd i want to stop it factorisding.
for 52 here,
52=(2^1)*26
here 26 is even.
so again, 52=(2^2)*13. i want matlab to give me this expression for any even number.
Another example is, 80=(2^1)*40, next 80=(2^2)*20, again, 80=(2^3)*10, again 80=(2^4)*5. in here d=5, which is odd. this is the expression i want for 80.
I don't need to see the whole steps as its calculating the powers of 2. i just want it to give me the last expression.
Does anyone have an idea how to do it?
0 commentaires
Réponse acceptée
Guillaume
le 13 Fév 2019
Modifié(e) : Guillaume
le 13 Fév 2019
Can't you just use a loop?
function [exponent, multiplicand] = decompose(number)
validateattributes(number, {'numeric'}, {'integer', 'positive', 'even'});
for exponent = 1:1024 %no point going any higher. maximum exponent of a double is 1023
multiplicand = number / 2^exponent;
if mod(multiplicand, 2) == 1 %multiplicand is odd
break;
end
end
assert(exponent ~= 1024, 'no odd multiplicand found');
end
And actually, since there's only 1023 valid exponents, you could do it without a loop:
function [exponent, multiplicand] = decompose(number)
validateattributes(number, {'numeric'}, {'integer', 'positive', 'even'});
exponents = 1:1023;
multiplicands = number ./ 2.^exponents;
firstodd = find(mod(multiplicands, 2) == 1, 1);
exponent = exponents(firstodd);
multiplicand = multiplicands(firstodd);
end
0 commentaires
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!