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

조회 수: 11 (최근 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?

채택된 답변

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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by