-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimetest.c
63 lines (58 loc) · 1.26 KB
/
primetest.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
* Prime number generator using linked lists to keep track of found primes to reduce number of calculations
* Made by Joel Grunbaum
*/
#include <stdio.h>
#include <stdlib.h>
//Linked list
typedef struct node{
unsigned long long num;
struct node *next;
} list_t;
void add_node(list_t *lst);
void free_list(list_t *lst);
int prime(int reps){
int isprime;
list_t *head, *current;
//Main loop of program, loops through odd numbers and checks of they are factors of numbers in the list
for(unsigned long long n = 3; n<reps; n+=2){
head=malloc(sizeof(list_t));
current = head;
isprime=1;
while(current != NULL){
unsigned long long a = current->num;
if(a*a>n)
break;
if(a!=0){
if(n%a==0){
isprime = 0;
break;
}
}
current = current->next;
}
//Adds new primes to list
if(isprime == 1){
current = head;
while(current->next!=NULL){
current= current->next;
}
add_node(current);
current = current->next;
current->num = n;
}
free_list(head);
}
return 1;
}
void add_node(list_t *lst){
lst->next=malloc(sizeof(list_t));
lst->next->next=NULL;
}
void free_list(list_t *lst){
while(lst!=NULL){
list_t *temp=lst;
lst=lst->next;
free(temp);
}
}