Answer to Question #296777 in C for Kamal

Question #296777

Write a code to find the frequency of prime numbers from a queue


1
Expert's answer
2022-02-11T17:23:36-0500
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>


#define N 100
#define NMAX 100


typedef struct Node_ {
    int data;
    struct Node_*next;
} Node;


typedef struct Queue_ {
    Node* first;
    Node* last;
} Queue;


void init_queue(Queue* q) {
    q->first = q->last = NULL;
}


void inqueue(Queue* q, int v) {
    Node* node = (Node*) malloc(sizeof(Node));
    node->next = NULL;
    node->data = v;


    if (q->last == NULL) {
        q->first = q->last = node;
    }
    else {
        q->last->next = node;
        q->last = node;
    }
}


int dequeue(Queue* q) {
    int res = 0;
    Node* node;
    if (q->first) {
        res = q->first->data;
        node = q->first;
        q->first = q->first->next;
        free(node);


        if (q->first == NULL) {
            q->last = NULL;
        }
    }
    return res;
}


bool is_empty(Queue* q) {
    return q->first == NULL;
}


bool is_prime(int x) {
    int i;


    if (x < 2) {
        return false;
    }
    if (x == 2) {
        return true;
    }
    if (x%2 == 0) {
        return false;
    }


    i = 3;
    while (i*i <= x) {
        if (x%i == 0) {
            return false;
        }
        x += 2;
    }
    return true;
}


int main() {
    int x, i, count;
    double freq;
    Queue q;


    init_queue(&q);
    srand(time(NULL));


    for (int i=0; i<N; i++) {
        x = rand() % (NMAX-1) + 2;
        inqueue(&q, x);
    }


    count = 0;
    while (!is_empty(&q)) {
        x = dequeue(&q);
        if (is_prime(x)) {
            count++;
        }


    }


    freq = ((double) count) / N;
    printf("Fequency of prime number is %f\n", freq);


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS