-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest_prime.c
120 lines (110 loc) · 2 KB
/
largest_prime.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
INPUT: string containing the sorted array
INPUT: 1,2,3,4,5,6,13,29
OUTPUT: largest prime number from given string
OUTPUT: 29
Get input of string of unknown length from STDIN
COMPLEXITY: O(n)
*/
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<malloc.h>
char *pStr;
unsigned int len = 0 ;
unsigned int len2 = 0 ;
int *a;
void GetString()
{
unsigned int len_max = 128;
unsigned int current_size = 0;
pStr = malloc(len_max);
current_size = len_max;
int c;
if(pStr != NULL)
{
//accept user input until hit enter or end of file
while (( c = getchar() ) != '\n')
{
pStr[len++]=(char)c;
//if len reached maximize size then realloc size
if(len == current_size)
{
current_size = len+len_max;
pStr = realloc(pStr, current_size);
}
}
pStr[len] = '\0';
}
}
void GetIntArray()
{
int temp = len,i=0,j=0,k=0 ;
char temporary[256];
a = (int*)malloc(sizeof(int)*temp);
while(temp--)
{
if(pStr[i] != ',')
{
temporary[k] = pStr[i];k++;
}
else
{
a[j] = atoi(temporary);j++;k=0;
}i++;
}
a[j] = atoi(temporary);j++;k=0;
len2 = j;
}
void FreeString()
{
free(pStr);
pStr = NULL;
}
void FreeIntArray()
{
free(a);
a = NULL;
}
void PrintString()
{
printf("\n%s \n\n",pStr);
}
bool IsPrime(int num)
{
bool flag = false;
int i = 3;
if(num == 3) flag = true;
else if(!(num % 2 == 0))
{
for(;i<num; i+=2)
{
if(num % i == 0) flag = false;
else flag = true;
}
}
printf("\n%d\n",flag);
return flag;
}
int main()
{
GetString();
GetIntArray();
//printf("\nLEN : %d\n",len);
//PrintString();
int size = len2,temp,i=0;
int max = 0;
while( size-- )
{
temp = (a[i]);
if(IsPrime(temp))
{
if(max < temp) max = temp;
}
i++;
}
printf("%d",max);
FreeString();
FreeIntArray();
return 0;
}