-
Notifications
You must be signed in to change notification settings - Fork 0
/
003.c
88 lines (68 loc) · 1.67 KB
/
003.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
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <limits.h>
#include <errno.h>
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
typedef long int32;
typedef long long int64;
typedef unsigned long uint32;
typedef unsigned long long uint64;
#define MAX_FACTORS 100
bool is_prime(uint64 value);
int main(int argc, char **argv)
{
uint64 arg = 0;
uint64 factors[MAX_FACTORS];
char *str, *endptr;
if (argc < 2)
{
printf("No argument.\n");
exit(EXIT_FAILURE);
}
errno = 0;
str = argv[1];
arg = strtoull(str, &endptr, 0);
if (errno == ERANGE || arg == ULLONG_MAX || arg == 0 && errno != 0)
{
printf("Value conversion failed (strtoull).\n");
exit(EXIT_FAILURE);
}
printf("Argument value is %llu.\n", arg);
uint64 work_arg = arg;
uint64 root_arg = ((uint64)sqrtl((long double)arg)) + 1;
uint64 i;
uint64 factor_index = 0;
printf("Factors: ");
for (i = 2; i < root_arg; i++)
{
if (work_arg % i == 0 && is_prime(i))
{
factors[factor_index++] = work_arg;
work_arg = work_arg / i;
printf("%llu ", i);
}
if (factor_index == MAX_FACTORS)
{
printf("Number of factors exceeded %i. Quitting.\n", MAX_FACTORS);
exit(EXIT_FAILURE);
}
}
printf("\nThe largest factor of %llu is %llu.\n", arg, factors[factor_index-1]);
exit(EXIT_SUCCESS);
}
bool is_prime(uint64 value)
{
uint64 i, root_value_plus_one;
root_value_plus_one = ((uint64)sqrtl((long double)value)) + 1;
for (i = 2; i < root_value_plus_one; i++)
{
if (value % i == 0)
{
return FALSE;
}
}
return TRUE;
}