使用链表实现C语言N阶乘的笨办法
在C语言中,实现N阶乘的程序可以使用链表来处理大数计算。这种方法虽然称不上最优,但它在处理超大数时非常实用。以下是验证过可运行的N阶乘链表程序:
#include
#include
// 链表节点定义
struct Node {
int data;
struct Node* next;
};
// 初始化链表节点
struct Node* initNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 链表尾插法
void append(struct Node** head_ref, int new_data) {
struct Node* newNode = initNode(new_data);
if (*head_ref == NULL) {
*head_ref = newNode;
return;
}
struct Node* temp = *head_ref;
while (temp->next != NULL) temp = temp->next;
temp->next = newNode;
}
// 链表反向打印
void printListReverse(struct Node* node) {
if (node == NULL) return;
printListReverse(node->next);
printf("%d", node->data);
}
// 实现阶乘的大数乘法
void multiply(struct Node** head_ref, int x) {
struct Node* temp = *head_ref;
int carry = 0;
while (temp != NULL) {
int prod = temp->data * x + carry;
temp->data = prod ;
carry = prod / 10;
temp = temp->next;
}
while (carry) {
append(head_ref, carry );
carry /= 10;
}
}
// 计算N的阶乘
void factorial(int n) {
struct Node* result = initNode(1);
for (int x = 2; x <= n; x++) {
multiply(&result, x);
}
printf("%d! = ", n);
printListReverse(result);
printf("
");
}
int main() {
int n = 20; // 示例:计算20的阶乘
factorial(n);
return 0;
}
此程序通过链表将大数存储为倒序的数字列表,从而实现阶乘计算。尽管这种方法较为笨拙,但它能有效解决常规方法无法处理的超大数。
956B
文件大小:
评论区