-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem004.c
98 lines (90 loc) · 2.42 KB
/
Problem004.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
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
/**
* Author: Austin Derrow-Pinion
* Purpose: Solve Problem 4 on Project Euler
* Language: C
*
* Brute force method would take way too long for a computer to find
* the largest palindrome of any multiple of numbers with at least 2 digits.
* Once the algorithm worked for two digit palindromes, the algorithm for
* any number of digits only changes two lines. The i=__ statement and the
* while(second < ___) statement.
*/
bool isPalindrome(int i) {
char s[11];
int j, size;
sprintf(s, "%ld", i);
size = strlen(s);
for (j = 0; j < size / 2; j++) {
if (s[j] != s[size - j - 1]) {
return false;
}
}
return true;
}
int twoDigitPalindrome() {
int i, first, second, output = -1;
for (i = 198; i > 1; i--) {
first = i / 2;
if (first + first == i) second = first;
else second = first + 1;
while (second < 100) {
if (first * second > output) {
if (isPalindrome(first * second))
output = first * second;
}
second++;
first--;
}
if (output > 0) return output;
}
return output;
}
int threeDigitPalindrome() {
int i, first, second, output = -1;
for (i = 998001; i > 1; i--) {
first = i / 2;
if (first + first == i) second = first;
else second = first + 1;
while (second < 1000) {
if (first * second > output) {
if (isPalindrome(first * second))
output = first * second;
}
second++;
first--;
}
if (output > 0) return output;
}
return output;
}
int fourDigitPalindrome() {
int i, first, second, output = -1;
for (i = 99980001; i > 1; i--) {
first = i / 2;
if (first + first == i) second = first;
else second = first + 1;
while (second < 10000) {
if (first * second > output) {
if (isPalindrome(first * second))
output = first * second;
}
second++;
first--;
}
if (output > 0) return output;
}
return output;
}
int main() {
// if(isPalindrome(9210129)) printf("yes");
int largestTwoDigitPalindrome = twoDigitPalindrome();
printf("The largest palindrome made from the product of two 2-digit numbers is: %i\n", largestTwoDigitPalindrome);
int largestThreeDigitPalindrome = threeDigitPalindrome();
printf("The largest palindrome made from the product of two 3-digit numbers is: %i\n", largestThreeDigitPalindrome);
int largestFourDigitPalindrome = fourDigitPalindrome();
printf("The largest palindrome made from the product of two 4-digit numbers is: %i\n", largestFourDigitPalindrome);
return 0;
}