aboutsummaryrefslogtreecommitdiff
path: root/challenge-164/duncan-c-white/C/ch-1.c
blob: 44a1f6924c2cb5cab5f5bfaa0e5a7e30ff841bb0 (plain)
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
/* 
 * TASK #1 - Prime Palindrome
 * 
 * GUEST LANGUAGE: THIS IS THE C VERSION OF ch-1.pl.
 */ 

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <ctype.h>

#include "primes.h"



bool debug=false;


// int n = process_singlearg( argc, argv );
//	Process the -d flag, and check that there is a single
//	remaining argument, return it's numeric value.
int process_singlearg( int argc, char **argv )
{
	int arg=1;
	if( argc>1 && strcmp( argv[arg], "-d" ) == 0 )
	{
		debug = true;
		arg++;
	}

	int left = argc-arg;
	if( left != 1 )
	{
		fprintf( stderr,
			"Usage: prime-palindrome [-d] firstN\n" );
		exit(1);
	}

	// element is in argv[arg]

	if( debug )
	{
		printf( "debug: remaining argument is in arg=%d, firstn=%s\n",
			arg, argv[arg] );
	}

	return atoi( argv[arg] );
}


/*
 * bool ispal = ispalindrome( x );
 *	Return 1 iff $x is palindromic in base 10, otherwise 0.
 */
bool ispalindrome( int x )
{
	char str[20];
	sprintf( str, "%d", x );
	int len = strlen(str);
	for( int i=0; i<len/2; i++ )
	{
		if( str[i] != str[len-1-i] )
		{
			return 0;
		}
	}
	return 1;
}


int main( int argc, char **argv )
{
	int firstn = process_singlearg( argc, argv );
	int *primes = primes_upto( firstn );

	//bool ispal = ispalindrome( firstn );
	//printf( "ispal(%d)? %d\n", firstn, (int)ispal );

	printf( "Palindromic primes up to %d\n", firstn );
	for( int i=0; primes[i] > 0; i++ )
	{
		if( ispalindrome( primes[i] ) )
		{
			printf( "%d\n", primes[i] );
		}
	}

	free( primes );
	return 0;
}