Expressing an even number in powers of 2 and a multiple of an odd number.
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Guillaume
2019-2-13
编辑:Guillaume
2019-2-13
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 个评论
更多回答(1 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!