-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem_042.c
57 lines (46 loc) · 1.09 KB
/
problem_042.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
#include <ctype.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#define MAXLEN 100
/* word_value: return the sum of each letter value in string s */
int32_t word_value(char *s)
{
int32_t val;
for (val = 0; *s != '\0'; ++s)
val += (*s - 'A' + 1);
return val;
}
/* is_triangular: return 1 if n is a triangular number (it can be written as
* m(m+1) / 2 ) */
int32_t is_triangular(int32_t n)
{
int32_t m = (int32_t) sqrt(n*2);
return m*(m+1) / 2 == n;
}
/* read_word: read a word from a file that is like "A","ABILITY","ABLE"... */
int32_t read_word(FILE *fp, char *dest)
{
int32_t c;
/* skip quotes and comma */
while ((c = fgetc(fp)) != EOF && !isupper(c))
;
*dest++ = c;
/* read letters until it finds a comma or a quote */
while ((c = fgetc(fp)) != EOF && isupper(c))
*dest++ = c;
*dest = '\0';
return c;
}
int32_t main(void)
{
FILE *fp;
char word[MAXLEN];
int32_t answer = 0;
fp = fopen("problem_026-050/p042_words.txt", "r");
while (read_word(fp, word) != EOF)
if (is_triangular(word_value(word)))
++answer;
printf("Problem 42: %d\n", answer);
return 0;
}