Printing Multiplication Tables with C++

I heard about this challenge online today, and thought about it for a few seconds before diving in. The object is to write a program that prints the multiplication table from 1 to 12, but that didn’t seem good enough to me. There has to be some utility to the program, not just something trivial. I wanted the user to be able to specify what size table they want.

Enter a natural number: 3
0 x 0 = 0	1 x 0 = 0	2 x 0 = 0	3 x 0 = 0
0 x 1 = 0	1 x 1 = 1	2 x 1 = 2	3 x 1 = 3
0 x 2 = 0	1 x 2 = 2	2 x 2 = 4	3 x 2 = 6
0 x 3 = 0	1 x 3 = 3	2 x 3 = 6	3 x 3 = 9

Returning 12 is certainly doable, but what about 144? While that particular input will not look very good on the command line, it still returns the result: 144 x 144 = 20736. And what about 1,000? It takes a little while, but it sure gets there. There are a couple of for loops (thus, input of 1,000 is lengthy in returning), and there’s a sanity check for negative input. Other than that, this one is very lean.

~Jonathan

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
/*
 * Programmer:       Jonathan Landrum
 * Date:             10 March 2012
 *
 * Program:          times.cpp
 * Purpose:          Returns the times table of the size the
 *                   user specifies.
 *
 * Assumptions:      1.) Input is in integer form. Real input
 *                       will cause the program to exit.
 */
 
#include <iostream>
using namespace std;
 
int main() {
	// Variables
	int input;
 
	// Introduce the program
	cout << "--------------------------" << endl;
	cout << "-      Times Tables      -" << endl;
	cout << "--------------------------" << endl;
	cout << endl;
	cout << "This program takes input" << endl;
	cout << "of an integer and returns" << endl;
	cout << "the times tables up to the" << endl;
	cout << "number specified." << endl;
	cout << endl;
	cout << "--------------------------" << endl;
	cout << endl;
	cout << "Enter a natural number: ";
	cin  >> input;
 
	// Sanity check
	while (input < 0) {
		cout << endl;
		cout << "ERROR: Bad input" << endl;
		cout << "Only positive input allowed" << endl;
		cout << endl;
		cout << "Enter a natural number: ";
		cin  >> input;
	} // End sanity check
 
	// Perform calculations
	for (int c = 0; c <= input; ++c) {
		for (int i = 0; i <= input; ++i)
			cout << i << " x " << c << " = " << i * c << "\t";
		cout << endl;
	} // End for
 
	// Exit program
	cout << endl;
	cout << "\\\\//_ Live long and prosper." << endl;
} // End main

Finding the Least Common Multiple Using Euclid’s Algorithm and C++

I saw this challenge in the comments section of an article on Coding Horror called “The Non-Programming Programmer”. This article is actually a response to the various tweets and comments he’s gotten on his first article on the subject, “Why Can’t Programmers… Program?”, the very article that started it all for me and this site with FizzBuzz.

The comment I referenced earlier was by one Sergey Kuznetsov, who mentioned writing a program to find the Least Common Multiple of two integers. It took me a while to figure this one out. Doing the work is one thing; telling a computer how to do it is another thing entirely. I can make a mean Peanut Butter and Jelly Sandwich, but the literal, step-by-step algorithm for that thing is horrendous. So, boiling down the process I use to find the Least Common Multiple was not easy, and in the end I trashed my method in favor of Euclid’s Algorithm.

This method is thousands of times faster than the iterative method I was devising (and it actually converges, which mine had yet to do), plus it can easily be plugged into a larger, more elaborate program for finding, say, relative primes. All in all, I’ve learned a lot, and have been introduced to an algorithm I never would have thought of on my own. Thank you, Wikipedia.

~Jonathan

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
/*
 *	Programmer:  Jonathan Landrum
 *	Date:        2 March 2012
 *
 *	Program:     leastCommonMultiple.cpp
 *	Purpose:     Finds the least common multiple
 *	             of two natural numbers using
 *	             Euclid's Algorithm.
 *
 *	Assumptions: 1.) Input is in natural number
 *	                 form. Real input will be cast
 *	                 to an integer, and negative
 *	                 input will cause a loop until
 *	                 positive input is received.
 */
 
#include <iostream>
 
using namespace std;
 
// --------------------------------------------------
// main():
// --------------------------------------------------
int main () {
 
	// Variables
	int input1 = 0;		// First input variable from user
	int input2 = 0;		// Second input variable from user
	int smaller = 0;	// Smaller of the two input variables
	int larger = 0;		// Larger of the two input variables
	int remainder = 0;	// The remainder from continued modulo
	int result = 0;		// Results returned from the operation
 
	// Introduce the program
	cout << endl;
	cout << "------------------------------------------" << endl;
	cout << "-    Least Common Multiple Calculator    -" << endl;
	cout << "------------------------------------------" << endl;
	cout << endl;
	cout << "This program uses Euclid's Algorithm to" << endl;
	cout << "find the least common multiple of two" << endl;
	cout << "natural numbers." << endl;
	cout << endl;
 
 
	// Get input from user
	cout << "Enter the first natural number: ";
	cin  >> input1;
	cout << endl;
 
	while (input1 < 1) {
		cout << "ERROR: Bad input" << endl;
		cout << "Enter the first natural number: ";
		cin  >> input1;
		cout << endl;
	} // End sanity check
 
	cout << "Enter the second natural number: ";
	cin  >> input2;
	cout << endl;
 
	while (input2 < 1) {
		cout << "ERROR: Bad input" << endl;
		cout << "Enter the second natural number: ";
		cin  >> input2;
		cout << endl;
	} // End sanity check
 
 
	// Find the smaller of the two
	if (input1 - input2 > 0) {
		smaller = input2;
		larger  = input1;
	} else {
		smaller = input1;
		larger  = input2;
	} // End if
 
	if (larger % smaller == 0) {
		result = larger;
	} else {
		remainder = larger % smaller;
		while (remainder != 0) {
			larger = smaller;
			smaller = remainder;
			remainder = larger % smaller;
		} // End while
		result = (input1 * input2) / smaller;
	} // End if
 
 
	// Return the results
	cout << "The least common multiple is " << result << endl << endl;
 
	cout << "\\\\//_ Live long and prosper." << endl;
	return (0);
} // End main

How To Create Your Own Command-Line User Interface

I wrote a program last semester that calculates complex arithmetic using Fortran, and with that program I also started dabbling in CLI design. I set out today to write a program that does nothing more than present a testbed for a command-line interface. You should be able to copy this code and apply it to any project as a template, substituting your own commands and conditions.

~Jonathan

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
121
122
123
124
125
126
127
/*
 *	Programmer:  Jonathan Landrum
 *	Date:        29 February 2012
 *
 *	Program:     userInterface.cpp
 *	Purpose:     To provide a testbed for
 *                   developing a useful CLI.
 *	Assumptions: None.
 */
 
#include <iostream>
#include <cstdlib>
 
using namespace std;
 
// --------------------------------------------------------
// main():
// --------------------------------------------------------
int main () {
 
	// Variables
	char   response;	// User response to the UI
	string input;		// User input to return
	string buffer;		// Disgarded carriage returns
	int    random;		// Random number for random phrase
 
	// Introduce the program
	cout << endl;
	cout << "-------------------------------" << endl;
	cout << "-    Hello World Generator    -" << endl;
	cout << "-------------------------------" << endl;
	cout << endl;
	cout << endl;
	cout << "ENTER A COMMAND:" << endl;
	cout << endl;
	cout << "     Echo a phrase........[E]" << endl;
	cout << "     Random Message.......[R]" << endl;
	cout << endl;
	cout << "     This help document...[?]" << endl;
	cout << "     EXIT.................[X]" << endl;
	cout << endl;
	cin  >> response;
	cout << endl;
 
 
	// Ensure we have a valid command
	while (response != 'e' && response != 'E' &&
	       response != 'r' && response != 'R' &&
	       response != 'x' && response != 'X' &&
	       response != '?') {
		cout << endl;
		cout << "Error:  << UNKNOWN COMMAND >>" << endl;
		cout << endl;
		cout << endl;
		cout << "ENTER A COMMAND: ";
		cin  >> response;
		cout << endl;
	} // End while
 
 
	// Keep the user in the loop unless they type "X"
	while (response != 'x' || response != 'X') {
		if (response == 'e' || response == 'E') {
			// Get rid of extraneous carriage returns
			getline(cin,buffer);
			cout << "Enter a string: ";
			getline(cin,input);
			cout << endl;
			cout << input << endl << endl;
		} else if (response == 'r' || response == 'R') {
			// Gives us a "random" seed from system time
			srand  (time(NULL));
			// Gives us a natural number from 1 to 5
			random = (rand() % 5) + 1;
			cout << "How to say hello in..." << endl;
			switch (random) {
				case 1:
					cout << "привет (Russian)" << endl;
					break;
				case 2:
					cout << "Hola (Spanish)" << endl;
					break;
				case 3:
					cout << "Hallo (German)" << endl;
					break;
				case 4:
					cout << "Bonjour (French)" << endl;
					break;
				case 5:
					cout << "Hello (English)" << endl;
					break;
				default:
					break;
			} // End random hello switch
			cout << endl;
		} else if (response == '?') {
			cout << "     Echo a phrase........[E]" << endl;
			cout << "     Random Message.......[R]" << endl;
			cout << endl;
			cout << "     This help document...[?]" << endl;
			cout << "     EXIT.................[X]" << endl;
			cout << endl;
		} else {
			break;
		} // End if
 
		cout << "ENTER A COMMAND: ";
		cin  >> response;
		cout << endl;
		while (response != 'e' && response != 'E' &&
		       response != 'r' && response != 'R' &&
		       response != 'x' && response != 'X' &&
		       response != '?') {
			cout << endl;
			cout << "Error:  << UNKNOWN COMMAND >>" << endl;
			cout << endl;
			cout << endl;
			cout << "ENTER A COMMAND: ";
			cin  >> response;
			cout << endl;
		} // End while
	} // End while
 
	// Exit
	cout << "\\\\//_ Live long and prosper." << endl;
	return (0);
} // End main

Swapping the Values of Two Variables Without Using a Third Variable

I’ve heard about this challenge before, and didn’t really think much of it at the time. Seemed superfluous to me to try to swap two variables without using a third one. But something I read today pushed me over the ledge to try it.

I was reading about the C++ Preprocessor, a separate program that calculates expressions before the program is compiled. I use at least one preprocessor directive in all my C++ programs, the #include <iostream> line right after the opening comments.

The book I was reading issued a challenge to use preprocessor commands to make a macro that swaps two variables, and the author went on to say, “If you’re a real hacker, write one that does not use a temporary variable declared outside the macro.” (Emphasis mine.) I couldn’t let that slip, so I wrote this program in response.

I want to point out that this endeavor would be better served as either a series of commands, or perhaps an inline function. But since the author asked for #define’s, that’s what I put.

~Jonathan

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
/*
 *	Programmer:  Jonathan Landrum
 *	Date:        26 February 2012
 *
 *	Program:     variableSwap.cpp
 *	Purpose:     This program swaps the values of
 *                   two variables, without using a
 *                   temporary variable.
 *	Assumptions: None.
 */
 
#include <iostream>
#define SWAP(one,two) { one ^= two; two ^= one; one ^= two; }
 
using namespace std;
 
// --------------------------------------------------
// main():
// --------------------------------------------------
int main () {
 
	// Variables
	int one, two;
 
	// Introduce the program
	cout << endl;
	cout << "-----------------------------------" << endl;
	cout << "-    Two-Variable Value Swapper   -" << endl;
	cout << "-----------------------------------" << endl;
	cout << endl;
	cout << "This program exchanges values of two" << endl;
	cout << "variables WITHOUT using a temporary" << endl;
	cout << "variable." << endl;
	cout << endl;
	cout << "Enter a value for variable 1: ";
	cin  >> one;
	cout << "Enter a value for variable 2: ";
	cin  >> two;
	cout << endl;
 
	cout << "Variable 1 is " << one << endl;
	cout << "variable 2 is " << two << endl;
	cout << endl;
	cout << "Swapping the values..." << endl << endl;
 
	// Main processing loop
	SWAP(one,two);
 
	// Return the results
	cout << "Variable 1 is now " << one << endl;
	cout << "Variable 2 is now " << two << endl;
 
	cout << endl;
	cout << "\\\\//_ Live long and prosper." << endl;
 
	return (0);
} // End main

C++ Checkerboard Printer

I ran across a coding challenge in a programming book that said create a program that prints out an 8 × 8 checkerboard using loops. Each box was to be five characters wide and three lines tall, and they gave a 2 × 2 example:

+-----+-----+
|     |     |
|     |     |
|     |     |
+-----+-----+
|     |     |
|     |     |
|     |     |
+-----+-----+

Sounds easy enough, right? It’s actually quite similar to — and much easier than — the character diamond challenge I found. The only difference is the sides are vertical, so there’s no mucking around with spaces. Here’s a sample output:

A checkerboard printout from a C++ program

The idea is to create a primary loop that controls rows, and then populate it with secondary loops to take care of columns: one for the top row and three for the side walls. Save the last row for after the loop, and bada bing, you’ve got a checkerboard. I anticipated spending hours on it, and was a bit let down to be done in five minutes. But nonetheless, here it is.

~Jonathan

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
/*
 *	Programmer:  Jonathan Landrum
 *	Date:        25 February 2012
 *
 *	Program:     checkerboard.cpp
 *	Purpose:     Prints a checkerboard of
 *	             user-defined size.
 *	Assumptions: None.
 */
 
#include <iostream>
 
using namespace std;
 
// --------------------------------------------------
// main():
// --------------------------------------------------
int main () {
 
	// Variables
	int counter, iterator, input;
 
	// Introduce the program
	cout << endl;
	cout << "----------------------------------" << endl;
	cout << "-    C++ Checkerboard Printer    -" << endl;
	cout << "----------------------------------" << endl;
	cout << endl;
	cout << "             +-----+" << endl;
	cout << "             |     |" << endl;
	cout << "             |     |" << endl;
	cout << "             |     |" << endl;
	cout << "             +-----+" << endl;
	cout << endl;
	cout << "This program takes user input of an" << endl;
	cout << "integer and prints a checkerboard" << endl;
	cout << "of that size." << endl;
 
	cout << "What size checkerboard do you want: ";
	cin  >> input;
 
	// Main processing loop
	for (counter = 0; counter < input; ++counter) {
 
		// Print the top line
		for (iterator = 0; iterator < input; ++iterator) {
			cout << "+-----";
		} // End for
		cout << "+" << endl;
 
		// Print the sides
		for (iterator = 0; iterator < input; ++iterator) {
			cout << "|     ";
		} // End for
		cout << "|" << endl;
 
		for (iterator = 0; iterator < input; ++iterator) {
			cout << "|     ";
		} // End for
		cout << "|" << endl;
 
		for (iterator = 0; iterator < input; ++iterator) {
			cout << "|     ";
		} // End for
		cout << "|" << endl;
	} // End for
 
	// Print the last line after the loop
	for (iterator = 0; iterator < input; ++iterator) {
		cout << "+-----";
	} // End for
	cout << "+" << endl;
 
	return (0);
} // End main

Converting Time in Seconds to Weeks, Days, Hours, Et Cetera

I found an interesting assignment in a C/C++ programming book I have. It was about converting seconds to minutes, and another about converting minutes/seconds to seconds. I decided to take that on, pushing it all the way to years. What this has actually become is an exercise in using modulo and division well.

The algorithm begins with calculating years, with each successive calculation containing all of the previous ones, and then changing the last operation from division to modulo. You have to do that in order to access the remainder left from the previous calculation. It’s more simple than it sounds. You only need to know ahead of time how many seconds are in a year, month, week, day, hour, and minute.

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
// ==================================================
// Programmer:  Jonathan Landrum
// Date:        20 February 2012
// ==================================================
// Program:     timeConverter.cpp
// Purpose:     Converts seconds input (integer) to
//              weeks, days, hours, minutes (etc.)
// Assumptions: 1.) Input is integer form. Floating
//                  point input will be rounded down
//                  to the nearest integer.
// ==================================================
 
#include <iostream>
using namespace std;
 
// --------------------------------------------------
// main():
// --------------------------------------------------
int main () {
 
	// Variables
	int years   = 0;
	int months  = 0; // 30 days
	int weeks   = 0;
	int days    = 0;
	int hours   = 0;
	int minutes = 0;
	int seconds = 0;
	unsigned long int input;
 
	// Introduce the program
	cout << endl;
	cout << "----------------------------" << endl;
	cout << "-      Time Converter      -" << endl;
	cout << "----------------------------" << endl;
	cout << endl;
	cout << "How many seconds to convert? ";
	cin  >> input;
 
	// Main processing loop
	years   = input / 31536000;
	months  = (input % 31536000) / 2592000;
	weeks   = ((input % 31536000) % 2592000) / 604800;
	days    = (((input % 31536000) % 2592000) % 604800) / 86400;
	hours   = ((((input % 31536000) % 2592000) % 604800) % 86400) / 3600;
	minutes = (((((input % 31536000) % 2592000) % 604800) % 86400) % 3600) / 60;
	seconds = ((((((input % 31536000) % 2592000) % 604800) % 86400) % 3600) % 60);
 
 
	// Return the results
	cout << "There are ";
	if (years != 0)
		cout << years << " years ";
 
	if (months != 0)
		cout << months << " months ";
 
	if (weeks != 0)
		cout << weeks << " weeks ";
 
	if (days != 0)
		cout << days << " days ";
 
	if (hours != 0)
		cout << hours << " hours ";
 
	if (minutes != 0)
		cout << minutes << " minutes ";
 
	if (seconds != 0) {
		if (input > 60)
			cout << "and " << seconds << " seconds ";
		else
			cout << seconds << " seconds ";
	} // End if. Will be rather uninpressive for input < 60.
 
	cout << "in " << input << " seconds." << endl;
 
	cout << endl;
	cout << "\\\\//_ Live long and prosper." << endl;
	cout << endl;
	return (0);
} // End main

Here’s a sample output from the program:

Time Converter

I’ve checked the output numerous times and it’s correct. The only thing it doesn’t do is Leap Year (as in calculating the date based on the Unix Epoch, for example), so it will return a higher number for days, weeks, etc. on those years.

Making correct Leap Year output could be done, but it would require inputting a starting year and calculating from there, and that’s not what this program does. It’s not a static time, for instance. It’s a general time, as in “how many days are in x seconds”. But the algorithm can be adapted for use in a time-since program. Perhaps I will write that one next.

~Jonathan

Calculating Factorials with an Iterative Method

I wrote yesterday about calculating factorials with a recursive function, and I mentioned that there was another method you could use to find the answer. I modified the program I wrote yesterday by completely removing the factorial() function and replacing the call to that function with a simple for loop.

There are times when a recursive approach is better, and there are times when an iterative approach is better. In this case, both come out with the answer in about the same time, but it’s up to you to determine which to use in which case. Obviously, if you have an algorithm that gets straight to the answer, choose that one! When I wrote about finding the difference of sums the other day, I skipped all the looping and got straight to the point with Euler’s summation algorithms. That was a one-step calculation, versus n cycles through a loop.

If not more efficient, the iterative approach is certainly more terse in this case. I cut out 22 lines of code in removing the factorial() function. But be cautious in pursuing terseness. Brevity and legibility are often inversely proportional to each other.

~Jonathan

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
// ==================================================
// Programmer:  Jonathan Landrum
// Date:        16 February 2012
// ==================================================
// Program:     noFunctions.cpp
// Purpose:     Calculates up to 20!, sans functions.
// Assumptions: None.
// ==================================================
 
#include <iostream>
using namespace std;
 
// --------------------------------------------------
// main():
// Self-containing program
// --------------------------------------------------
int main () {
 
	// Variables
	long answer = 1;
	long response;
 
	// Introduce the program
	cout << endl;
	cout << "-----------------------------------------" << endl;
	cout << "-    Calculating Factorials up to 20!   -" << endl;
	cout << "-----------------------------------------" << endl;
	cout << endl;
	cout << "This program calculates factorials up to" << endl;
	cout << "20!. Larger factorials are impossible." << endl;
	cout << endl;
 
	// Get user response, then do some sanity checks
	do {
		cout << "Enter a positive integer less" << endl;
		cout << "than 21 to calculate: ";
		cin  >> response;
		cout << endl;
	} while (response < 0 || response > 20);
 
	// Calculate the answer
	for (int c = response; c > 1; c--)
		answer = answer * c;
 
	// Return the results
	cout << response << "! is " << answer << endl;
 
	return (0);
} // End main

Calculating Factorials with a Recursive Function

I initially set out with this program to find 100! (factorial), but integer space is simply not that large. (I’ve been doing a lot of big number things the last few days.) So, short of importing a library that can handle big numbers, we’ll have to settle for factorials less than 20.

The formal definition of factorial is “n! = the product as k goes from 1 to n of k”.

Factorial Definition

What that means is, that for every value of k as k goes from 1 to n, n! is the product of the multiplication of those values together. So 10! is 10 × 9 × 8 × … × 3 × 2 × 1, which is 3,628,800. We define 0! as 1 for a few reasons, mainly because it makes sense in combinatorics. If you think about it, it’s easy to see why: you can pick 0 items from an empty set only 1 way (by picking nothing at all).

Empty Set

As such, this program will calculate a factorial accurately from 0 to 20 inclusive, and will round real input to the lowest integer. To “factorial” non-integers, the Gamma Function is necessary, and it is essentially a generalization of factorial. The Gamma Function will work with both real and complex numbers. That is why this program rounds real input down to the nearest integer. Perhaps I’ll tackle the Gamma Function another day. ;~]

This program makes use of recursion to solve the factorial. You could also solve this particular problem by taking the user input as an integer and then using a for loop with that input as the counter, decrementing by 1 with each pass through the loop.

~Jonathan

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
// ==================================================
// Programmer:  Jonathan Landrum
// Date:        15 February 2012
// ==================================================
// Program:     20Factorial.cpp
// Purpose:     Calculates up to 20! using a function
// Assumptions: None.
// ==================================================
 
#include <iostream>
using namespace std;
 
// Function Prototypes
long factorial(long);
 
// --------------------------------------------------
// main():
// Calls factorial() and returns the answer
// --------------------------------------------------
int main () {
 
	// Variables
	long answer  = 0;
	int  response;
 
	// Introduce the program
	cout << endl;
	cout << "-----------------------------------------" << endl;
	cout << "-    Calculating Factorials up to 20!   -" << endl;
	cout << "-----------------------------------------" << endl;
	cout << endl;
	cout << "This program calculates factorials up to" << endl;
	cout << "20!. Larger factorials are impossible." << endl;
	cout << endl;
 
	// Get user response, then do some sanity checks
	do {
		cout << "Enter a positive integer less" << endl;
		cout << "than 21 to calculate: ";
		cin  >> response;
		cout << endl;
	} while (response < 0 || response > 20);
 
	// Main processing call
	answer = factorial(response);
 
	// Return the results
	cout << response << "! is " << answer << endl;
 
	return (0);
} // End main
 
// --------------------------------------------------
// factorial():
// Recursive function; makes repeated calls to itself
// in order to find n!. Works for up to 20!.
// --------------------------------------------------
long factorial(long in) {
 
	// Variables
	long out;
 
	// Run recursive calculation
	if (in == 0 || in == 1)
		out = 1;
	else
		out = in * factorial (in - 1);
 
	// Return the results
	return out;
}

Happy Valentine’s Day (in C++)

We wrote this program in C/C++ yesterday in honor of St. Valentine’s Day. It prints a simple ASCII heart with a geeky poem written above it:

Roses are #FF0000;
    Violets are #0000FF;
All my base
    Are belong to you!

Valentine's Day Heart

I showed it to my wife last night, and she was happy to receive it. But be warned, it’s no stand-in for actual flowers and candy.

~Jonathan

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
// Happy St. Valentine's Day!
 
#include <iostream>
using namespace std;
 
int main() {
	int ht;
	int row;
	int index;
	int topHt;
	int initSpace;
	do {
		cout << "Enter the height of your heart: ";
		cin  >> ht;
		if (ht < 3) {
			cout << "have a bigger heart!" << endl;
		} // end if
	} while (ht < 3);
 
	// get it down a couple spaces, and center a message to your Valentine
	cout << endl << endl;
	cout << "                               Roses are #FF0000;" << endl;
	cout << "                                   Violets are #0000FF;" << endl;
	cout << "                               All my base" << endl;
	cout << "                                   Are belong to you!" << endl << endl;
 
	// draw top of the heart
	topHt = ht + 1;
	initSpace = 40 - 2 * ht;
 
	// loop for each top row
	for (row = 2; row < topHt; row++) {
 
		// loop for centering spaces
		for (index = 0; index < initSpace; index++)
			cout << " ";
 
		// loop for initial spaces
		for (index = 0; index < (topHt - row); index++)
			cout << " ";
 
		// loop for right atrium (left side)
		for (index = 0; index < (row * 2 - 1); index++)
			cout << "*";
 
		// loop for aorta :~]
		for (index = 0; index < (2 * (topHt - row) - 1); index++)
			cout << " ";
 
		// loop for left atrium (right side)
		for (index = 0; index < (row * 2 - 1); index++)
			cout << "*";
 
		cout << endl;
	} // end main for
 
	// draw bottom of the heart
	ht = ht * 2 + 1;
	for (row = ht; row > 0; row--) {
 
		// loop for centering spaces
		for (index = 0; index < initSpace; index++)
			cout << " ";
 
		// loop for spaces
		for (index = 0; index < (ht - row); index++)
			cout << " ";
 
		// loop for asterisks
		for (index = 0; index < (row * 2 - 1); index++)
			cout << "*";
 
		cout << endl;
	} // end main for
 
	// add some more spacing at the end for looks
	cout << endl << endl;
 
	return 0;
 
} // end main

Adding the Prime Numbers Less Than 2,000,000

I attempted to solve this problem using Fortran, because I have a soft spot for that language. However, Fortran is limited in integer reproduction. The largest number produceable using a 32-bit integer data type is 2,147,483,647. The sum of primes greater than 2,000,000, however, is much larger than that. So what I noticed first was my number was wrong. To find where the problem was, I decided to print my running sum as it was tallying the numbers. I then noticed that it went negative quite a few times, which means it ran out of space to hold the number. I knew then what I had to do: convert it to C++ and change the integer to a long integer, which has a 64-bit space on C++. Doing that solved my problem, and I came out (finally) with the correct answer.

~Jonathan

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
// ==================================================
// Programmer:  Jonathan Landrum
// Date:        10 February 2012
// ==================================================
// Program:     sumOfPrimes.cpp
// Purpose:     Adds together the prime numbers less
//              than 2,000,000.
// Assumptions: None.
// ==================================================
 
#include <iostream>
using namespace std;
 
// --------------------------------------------------
// Function prototypes
// --------------------------------------------------
bool prime(int);
 
 
// --------------------------------------------------
// main():
// Calls the prime() function to determine which
// numbers are prime, and then adds them to the sum.
// --------------------------------------------------
int main () {
 
	// ------------------------------------------
	// Variables
	// ------------------------------------------
	int  counter = 1;
	long sum = 0;
 
	// ------------------------------------------
	// Introduce the program
	// ------------------------------------------
	cout << endl;
	cout << "---------------------------" << endl;
	cout << "-      Sum of Primes      -" << endl;
	cout << "---------------------------" << endl;
	cout << endl;
	cout << "This program adds the prime" << endl;
	cout << "numbers less than 2,000,000" << endl;
	cout << endl;
 
	// ------------------------------------------
	// Main processing loop
	// ------------------------------------------
	while (counter < 2000000) {
		if (prime(counter))
			sum += counter;
		counter += 2;
	} // End while
 
	// ------------------------------------------
	// Return the results
	// ------------------------------------------
	cout << sum << endl;
	cout << "-----------------------------" << endl;
	cout << "\\\\//_ Live long and prosper." << endl;
	return (0);
} // End main
 
 
// --------------------------------------------------
// prime():
// Determines if a number is prime
// --------------------------------------------------
bool prime (int n) {
 
	// Variables
	bool result;
	int  i;
 
	// Do work
	if (n <= 1) {
		result = false; // 1 is not prime
 
	} else if ((n == 2) || (n == 3)) {
		result = true; // Hard code 2 and 3
 
	} else if (n % 2 == 0) {
		result = false; // Get rid of evens
 
		/* All other cases are out, so now we check
		 to see if n is divisible by the odd
		 numbers from 3 on. */
	} else {
		i = 3;
		result = true; // Assume it's prime, then prove
 
		while (true) {
			/* If i^2 is not a root of n, or if
			 n % i == 0. (Won't be larger than
			 the square.) */
			if ((i * i > n) || (n % i == 0))
				break;
			i += 2; // Iterate by 2 to get odds
		} // End while
 
		// Record the answer
		if (i * i > n)
			result = true;
		else
			result = false;
	} // End if
 
 
	// Return the answer
	return result;
}