フィルターのクリア

how to find the largest power of 2 that a number is divisible?

6 ビュー (過去 30 日間)
Mnr
Mnr 2015 年 5 月 11 日
回答済み: Alfonso Nieto-Castanon 2015 年 5 月 12 日
Hello all,
How can I write a code that finds the largest integer power of 2 that a number is divisible? For instance, the largest power of 2 that 12 is divisible, is 4, the largest power of 2 that 20 is divisible is 4 as well, while the largest power of 2 that 24 is divisible is 8. Thanks.

採用された回答

per isakson
per isakson 2015 年 5 月 11 日
Hint:
>> factor(12)
ans =
2 2 3

その他の回答 (2 件)

Joseph Cheng
Joseph Cheng 2015 年 5 月 11 日
You can use the function factor() since it returns the prime factors of the input number. So since it breaks it down to the prime factors the number of 2s being return will make up the largest power of 2 that is still divisible.
x = randi(100);
y = factor(x);
two = y==2;
two = prod(y(two))
disp([x two])

Alfonso Nieto-Castanon
Alfonso Nieto-Castanon 2015 年 5 月 12 日
I know this is already answered but the typical/minimal-computation answer for this is:
bitand(x,-x,'int64')
(i.e. find the last 1 in the decimal representation of the original number)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by