Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C คำนวณ Log Base 2 แบบ Recursive

คำนวณค่า log₂(n) โดยใช้การหารซ้ำด้วย 2 แบบ recursive ซึ่งเทียบเท่ากับการหาจำนวนครั้งที่หาร 2 ได้จนเหลือ 1

ตัวอย่าง

Input: 20 → Output: 4 (เพราะ 2⁴=16 ≤ 20 < 32=2⁵)
Input: 64 → Output: 6 (2⁶=64)

อัลกอริทึม

log2n(num) = (num > 1) ? 1 + log2n(num/2) : 0

โค้ดตัวอย่าง

#include <stdio.h>

unsigned int log2n(unsigned int num) {
    return (num > 1) ? 1 + log2n(num / 2) : 0;
}

int main() {
    unsigned int num = 20;
    printf("%u\n", log2n(num));
    return 0;
}

ผลลัพธ์

4