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

11 ビュー (過去 30 日間)
rihan jericho
rihan jericho 2019 年 2 月 13 日
コメント済み: rihan jericho 2019 年 2 月 13 日
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?

採用された回答

Guillaume
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

その他の回答 (1 件)

M
M 2019 年 2 月 13 日
I would do something like
a = 80;
r = 1;
d = a/2;
while mod(d,2)==0
r=r+1;
d=d/2;
end
  1 件のコメント
rihan jericho
rihan jericho 2019 年 2 月 13 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by