When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
1 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
#include <stdio.h>
#include <stdlib.h>
// structure Farey fraction nodes
struct node {
int num; // numerator
int den; // denomenator
struct node* next; // points to the next node
};
// function that creates and adds the Farey functions in appropriate places
// within the linked list
struct node* makeFareyNode(int num, int den, struct node* next) {
// allocates memory for new nodes
struct node* newNode = (struct node*)malloc(sizeof(struct node));
if (newNode == NULL) {
fprintf(stderr, "Failed to allocate memory for the new node.\n");
exit(1);
}
// value assignment to members of structure
newNode->num = num;
newNode->den = den;
newNode->next = next;
return newNode;
}
// function prints the Farey sequence up to the user inputted level
void printFareySequence(int level) {
if (level < 1) {
printf("Level must be greater than or equal to 1.\n");
return;
}
// creates beginning and end nodes i.e. 0 and 1
struct node start = {0, 1, NULL};
struct node end = {1, 1, NULL};
start.next = &end;
// creates farey fractions up to user inputted level
for (int i = 1; i <= level; i++) {
struct node* prev = &start;
while (prev != NULL && prev->next != NULL) {
if (prev->den + prev->next->den <= i) {
struct node* newNode =
makeFareyNode(prev->num + prev->next->num,
prev->den + prev->next->den, prev->next);
prev->next = newNode;
prev = newNode;
}
prev = prev->next;
}
}
// prints the entierity of the Farey sequence
struct node* temp = &start; // assigns address of start node..pointer used to
// iterat e through the linked list
while (temp != NULL) { // stops when there are no more nodes to traverse
// through
struct node* innerTemp =
temp; // pointer will be used to traverse each linked list sequence
printf("(");
while (innerTemp != NULL) {
printf("%d/%d", innerTemp->num, innerTemp->den);
if (innerTemp->next != NULL) {
printf(", ");
}
innerTemp = innerTemp->next;
}
printf(")\n");
temp = temp->next;
}
// Free memory
temp = start.next;
while (temp != NULL) {
struct node* nextNode = temp->next;
free(temp);
temp = nextNode;
}
}
int main(int argc, char* argv[]) {
// checks validity of arguments i.e. how many arguments user inputted
if (argc != 2) {
printf("Usage: farey <n>\n\twhere n >=1 is the level of Farey sequence.\n");
return 1;
}
// prints level inputted by the user then the sequences up to that given level
int level = atoi(argv[1]);
printFareySequence(level);
return 0;
}
Farey Sequence, Linked List, Memory Allocation