voidloveYou(int n){ //n为问题规模 int i = 1; //爱你的程度 while (i <= n) { //每次+1 i++; printf("I Love You %d\n", i); for (int j = 1; j <= n; j++) { //嵌套循环两层 printf("I am Iron Man\n");//内层循环共执行n*n次 } } printf("I Love You More Than %d\n", n); }
voidloveYou(int n){ //n为问题规模 int i = 1; //爱你的程度 while (i <= n) { i = i * 2; //每次翻倍 printf("I Love You %d\n", i); } printf("I Love You More Than %d\n", n); }
时间复杂度分析:
(1)最深层语句频度为x
(2)循环结束时满足:
$$ 2^x>n \rightarrow x = log_2n + 1 $$
(3)时间复杂度:
$$ T(n) = O(x) = O(log_2n) $$
算法4:搜索数字型爱你
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<stdio.h> voidloveYou(int flag[], int n); intmain(void){ int flag[] = {1,2,3,4,5,6,7,8,9}; loveYou(flag,5); return0; }
voidloveYou(int flag[], int n){ //n为问题规模 printf("I Am Iron Man\n"); for (int i = 0; i < n; i++) { if (flag[i] == n) { printf("I Love You %d\n", i); break; } } }