ให้ค่า n เป็นค่าอินพุต และงานคือ คำนวณค่าของ Log n ผ่านฟังก์ชันและแสดงผล
ลอการิทึมหรือล็อกเป็นฟังก์ชันผกผันกับการยกกำลัง ซึ่งหมายถึงการคำนวณล็อก กำลังยกต้องคำนวณเป็นฐาน
IF
$$\log_b x\;\:=\:y\:than\:b^{y}=x$$
ชอบ
$$\log_2 64\;\:=\:6\:than\:2^{6}=64$$
ตัวอย่าง
Input-: Log 20 Output-: 4 Input-: Log 64 Output-: 6
อัลกอริทึม
Start In function unsigned int log2n(unsigned int num) Step 1-> Return (num > 1) ? 1 + log2n(num / 2) : 0 In function int main() Step 1-> Declare and assign num = 20 Print log2n(num) Stop
ตัวอย่าง
#include <stdio.h>
//We will be using recursive Approach used below is as follows
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