Expressing an even number in powers of 2 and a multiple of an odd number.

16 views (last 30 days)
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,
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?

Accepted Answer

Guillaume on 13 Feb 2019
Edited: Guillaume on 13 Feb 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
assert(exponent ~= 1024, 'no odd multiplicand found');
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);

More Answers (1)

M on 13 Feb 2019
I would do something like
a = 80;
r = 1;
d = a/2;
while mod(d,2)==0
  1 Comment
rihan jericho
rihan jericho on 13 Feb 2019
i also want it to give me the numbers stored, for example after the loop is done i want it to give me r=4, d=5 for 80. as 80 = (2^4)*5.
i also want to do it generally for which i casn use input. but this is the ultimate expression for any even number input i want.

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by