← Back to Index
Research & Engineering Archive

LPC 11. Recursion

By Jingnan Huang · March 31, 2025 · 1125 Words

Last Edit: 3/31/25

11.1 Recursive Functions by Definition
#

11.1.1 Euclidean Algorithm for GCD
#

$$ \text{GCD}(a, b) =\begin{cases}\text{GCD}(b, a - b) & \text{if } a > b \\text{GCD}(b, a) & \text{if } a < b \a & \text{if } a = b\end{cases} $$

#include <stdio.h>
int gcd(int a, int b);
int main(void) {
  int gcdAnswer = gcd(20, 8);
  printf("gcd(20, 8) = %d\n", gcdAnswer);
  return 0;
}
int gcd(int a, int b) {
  if (a == b) {
    return a;
  } else if (a > b) {
    return gcd(b, a - b);
  } else {
    return gcd(b, a);
  }
}

实际上 Recursion 严重降低了代码的可读性

GCD(20, 8)  GCD(8, 12)   20 - 8 = 12
GCD(8, 12)  GCD(8, 4)    12 - 8 = 4
GCD(8, 4)  GCD(4, 4)     8 - 4 = 4
GCD(4, 4) = 4             (因为两个数相等)

11.1.2 Factorial of a Number
#

n! = n × (n - 1) × (n - 2) × ... × 2 × 1
int factorial(int n) {
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact = fact * i;
    }
    return fact;
}
int factorial(int n);

int main(void) {
    int fact = factorial(4);
    return 0;
}

int factorial(int n) {
    return n * factorial(n - 1);
}

image.png

11.2 Recursion in Patterns
#

image.png

11.2.2 Print a Triangle of Stars
#

*****
****
***
**
*
#include <stdio.h>
void printRow(int n);
void printTriangle(int n);
int main(void) {
  int rows;
  printf("Enter number of rows:");
  scanf("%d", &rows);
  printTriangle(rows);
  return 0;
}
void printTriangle(int n) {
  if (n > 0) {
    printRow(n);
    printTriangle(n - 1);
  }
}
void printRow(int n) {
  if (n == 1) {
    printf("*\n");
  } else {
    printf("*");
    printRow(n - 1);
  }
}

11.2.3 Print an Inverted Triangle of stars
#

*
**
***
****
*****

11.2.4 Print a Pattern Recursively
#

*****
****
***
**
*
**
***
****
*****
printRow(n);              // 打印当前行
printPattern(n - 1);      // 递归打印下一层(更短的行)
printRow(n); 

11.3 Recursion in arrays
#

11.3.2 Palindrome Problem
#

#include <stdbool.h>
#include <stdio.h>
#include <string.h>
bool isPalindromeHelper(char *s, int low, int high) {
  if (low >= high)
    return true;
  else if (s[low] != s[high])
    return false;
  else
    return isPalindromeHelper(s, low + 1, high - 1);
}
bool isPalindrome(char *s) { 
    return isPalindromeHelper(s, 0, strlen(s) - 1); 
}
int main(void) {
  printf("isPalindrome(\"racecar\") = %d\n", isPalindrome("racecar"));
  printf("isPalindrome(\"e\") = %d\n", isPalindrome("e"));
  printf("isPalindrome(\"\") = %d\n", isPalindrome(""));
  printf("isPalindrome(\"race\") = %d\n", isPalindrome("race"));
  return 0;
}