Sum of Threes and Fives

I enjoy finding problems to solve with code. I found a page on the internet this afternoon that asked for the sum of all integers between 1 and 1,000 that are divisible by either 3 or 5. I immediately thought of the FizzBuzz program I wrote a while back, and realized the algorithm is actually quite similar. It’s just what you do with those threes and fives that’s different in this case. Either way, it was a fun couple of minutes putting to code what I’d been mulling over.

~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
// ==================================================
// Programmer:  Jonathan Landrum
// Date:        31 January 2012
// ==================================================
// Program:     threeOrFive.cpp
// Purpose:     Adds the integers between 1 and 1,000
//              that are divisible by either 3 or 5.
// Assumptions: None.
// ==================================================
 
#include <iostream>
#include <string>
using namespace std;
 
// --------------------------------------------------
// main():
// Does ALL the things!
// --------------------------------------------------
int main () {
 
	// ----------------------------------------------
	// Declare variables, not war
	// ----------------------------------------------
	int sum = 0;
	int c = 3;
 
	// ----------------------------------------------
	// Introduce the program
	// ----------------------------------------------
	cout << endl;
	cout << "----------------------------" << endl;
	cout << "-    Sum of 3's and 5's    -" << endl;
	cout << "----------------------------" << endl;
	cout << endl;
	cout << "This program adds together the" << endl;
	cout << "integers between 1 and 1,000" << endl;
	cout << "that are divisible by 3 or 5." << endl;
	cout << endl;
 
	// ----------------------------------------------
	// Main processing loop
	// ----------------------------------------------
	while (c < 1000) {
		if (c % 3 == 0 || c % 5 == 0) {
			sum += c;
			cout << c << endl;
		} else if (c % 3 == 0) {
			sum += c;
			cout << c << endl;
		} else if (c % 5 == 0) {
			sum += c;
			cout << c << endl;
		} // end if
		c++;
	} // end while
 
	// ----------------------------------------------
	// Return the answer
	// ----------------------------------------------
	cout << sum << endl;
 
	return (0);
} // End main

Fortran Prime Number Calculator

This program is one of my favorites I’ve written so far. It takes input from the user for the lower and upper bounds of a range of integers, calculates which numbers in that range are prime numbers, and outputs a list of the primes and the total number of primes found.

I tested the output of this program against this list of primes, and it checked out perfectly. It’s a fairly fast program, returning the primes between 1 and 1,000,000 in about 6 seconds on my machine. Only assumptions are the input must be in Real form. Text input will cause the program to throw an exception.

~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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
! ----------------------------------------------------------
! Programmer:   Jonathan Landrum
! Date:         21 September 2011
! Class:        CSC 204
! ----------------------------------------------------------
! Program:      primes.exe
! Purpose:      Calculates the number of prime numbers
!               there are in a given range, and returns
!               them in a list.
! Assumptions:  1.) Input from the user is in integer
!                   form. Text input will cause the
!                   program to fail. Real number input
!                   will be truncated into integers.
! ----------------------------------------------------------
 
PROGRAM primes
 
	IMPLICIT NONE
 
	INTEGER   :: total = 0, counter, lower, upper
	CHARACTER :: response
	LOGICAL   :: prime
 
	WRITE (*,*) '******************************************'
	WRITE (*,*) '*                                        *'
	WRITE (*,*) '*     FORTRAN PRIME NUMBER CALCULATOR    *'
	WRITE (*,*) '*                                        *'
	WRITE (*,*) '******************************************'
	WRITE (*,*)
	WRITE (*,*) 'Copyright (c) 2011 Jonathan Landrum'
	WRITE (*,*)
	WRITE (*,*) 'Calculates how many prime numbers are'
	WRITE (*,*) 'between the lower and upper bound given by'
	WRITE (*,*) 'the user, and returns the list of those'
	WRITE (*,*) 'prime numbers.'
	WRITE (*,*)
	WRITE (*,*) 'I wanted to use the Sieve of Eratosthenes'
	WRITE (*,*) 'algorithm, but could not figure out how to'
	WRITE (*,*) 'make it work. Perhaps later.'
	WRITE (*,*)
	WRITE (*,*) 'The output of this program has been checked'
	WRITE (*,*) 'against this list:'
	WRITE (*,*) 'http://primes.utm.edu/lists/small/100000.txt'
	WRITE (*,*)
	WRITE (*,*) '--------------------------------------------------'
	WRITE (*,*)
	WRITE (*,*) 'Would you like to continue? [Y/N]'
	WRITE (*,*)
	READ  (*,*) response
	WRITE (*,*)
 
	! Any response beginning with the letter "y" will work.
	WHILE (response == 'y' .OR. response == 'Y') DO
		WRITE (*,*)
		WRITE (*,*) 'What is the lower bound of numbers you'
		WRITE (*,*) 'would like to check?'
		WRITE (*,*)
		READ  (*,*) lower
		WRITE (*,*)
		WRITE (*,*) 'What is the upper bound of numbers you'
		WRITE (*,*) 'would like to check?'
		WRITE (*,*)
		READ  (*,*) upper
		WRITE (*,*)
 
		! If the user inputs a smaller number for the upper
		! bound, or if they input the same number, ask again
		WHILE ((upper - lower) <= 0) DO
			WRITE (*,*)
			WRITE (*,*) 'ERROR: Upper bound not higher than'
			WRITE (*,*) '       lower bound'
			WRITE (*,*)
			WRITE (*,*) 'What is the lower bound of numbers you'
			WRITE (*,*) 'would like to check?'
			WRITE (*,*)
			READ  (*,*) lower
			WRITE (*,*)
			WRITE (*,*) 'What is the upper bound of numbers you'
			WRITE (*,*) 'would like to check?'
			WRITE (*,*)
			READ  (*,*) upper
			WRITE (*,*)
		END DO ! END while upper is smaller
 
		! We have legitimate numbers
		counter = lower
		total = 0
		WHILE ((counter < upper).AND.(upper > 0)) DO
			IF (Prime(counter)) THEN
				WRITE (*, '(i0,1x)', ADVANCE = 'no') counter
				total = total + 1
			END IF ! Outputs the number
			counter = counter + 1
		END DO ! Processing loop
 
		WRITE (*,*)
		WRITE (*,*)
		WRITE (*,*) 'The number of primes between ',lower,' and ',upper,' is ',total,'.'
		WRITE (*,*)
		WRITE (*,*) '--------------------------------------------------'
		WRITE (*,*)
		WRITE (*,*) 'Would you like to continue? [Y/N]'
		WRITE (*,*)
		READ  (*,*) response
	END DO ! End Continue loop
	WRITE (*,*)
	WRITE (*,*) '\\//_ Live long and prosper.'
END PROGRAM primes
 
! ----------------------------------------------------------
! FUNCTION Prime:
! Determines if the input is a prime number. Returns T or F.
! ----------------------------------------------------------
LOGICAL FUNCTION Prime(n)
	IMPLICIT NONE
 
	INTEGER :: n, i
 
	IF (n <= 1) THEN                             ! 1 is not prime (Really, it's not)
		Prime = .FALSE.
	ELSE IF ((n == 2).OR.(n == 3)) THEN          ! Hardcode 2 and 3
		Prime = .TRUE.
	ELSE IF (MOD(n,2) == 0) THEN                 ! Get rid of evens
		Prime = .FALSE.
 
	! 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
		Prime = .TRUE.                           ! Assume it's prime, then prove
		DO                                       ! If i^2 is not a root of n, or if n%i = 0
			IF (i*i > n .OR. MOD(n,i) == 0) EXIT !(Won't be larger than the square)
			i = i + 2                            ! Iterate the counter by 2 to get odds
		END DO
 
		! Record the answer
		IF (i*i > n) THEN
			Prime = .TRUE.
		ELSE
			Prime = .FALSE.
		END IF
	END IF ! We have our answer
END FUNCTION Prime

Automating Terminal Commands in Mac OS X with Bash

Coming from the Linux world, Mac was somewhat familiar to me, yet somewhat foreign. One such example is the system hides most of the files and directories I was accustomed to seeing and using as a Linux user. Also, the terminal commands to show and re-hide these directories don’t follow standard Unix terminal syntax. So I had to do some researching to find what the commands even are, and then I could put them in a Bash script that could be run with a single click. But first, the commands:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
killall Terminal

The first line is the business end, the second one restarts Finder with the new setting, and the last makes sure Terminal closes afterward. And you can type these in a Terminal window right now and get the desired results. But what about automating this? Instead of typing all this out — and possibly misspelling it a time or two (ask me how I know) — let’s make a shell script that contains the commands, and keep it in our user directory for easy access:

1
2
3
4
#!/bin/bash
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
killall Terminal

The only difference this time is the new first line. That specifies which shell we’re using, in this case Bash. It’s called the shebang line, and it tells Terminal which program to use to interpret the commands. Copy and paste those three lines into TextEdit or your favorite text editor, and save it as show.sh or something similar. Then change the “TRUE” to “FALSE” at the end of the second line, like this:

1
2
3
4
#!/bin/bash
defaults write com.apple.finder AppleShowAllFiles FALSE
killall Finder
killall Terminal

and save that as hide.sh or something similar. Put these two files in your user root directory, in the same place where your Documents, Desktop, Music, and Pictures folders are.

An example directory layout

An example directory layout. Put show.sh and hide.sh in your user root like this.

Next we have to make them executable. Open Terminal (it will already be cd’d to your user root directory) and enter this command:

$ chmod +x show.sh && chmod +x hide.sh

This will make our two files executable. Now give them a whirl:

$ ./show.sh
$ ./hide.sh

The ./ tells Terminal to run that program. This should open your Finder window with hidden files and directories showing, but faded to show you the difference. And when you run hide.sh Finder will close and reopen, with those files and directories hidden. If that’s what you got, then continue to the final step to make them clickable. If not, go back through this tutorial and start from scratch. Make sure you’ve typed everything correctly.

The last step is open a Finder window and select show.sh, then type Command-i to bring up the information menu. Under the “Open with:” dropdown, select “Other…”, and in the window that pops up, scroll to the bottom to the “Utilities” directory, open that, and then scroll to Terminal and select it.

You may have to change the “Enable:” menu from “Recommended Applications” to “All Applications” in order to select it. Tick the “Always Open With” checkbox, and click “Add”. Repeat this last step for hide.sh.

Double-click show.sh and confirm it works, then do the same for hide.sh. If everything works as expected, you’re all set! You can access these programs from the command line or from Finder the way you’ve done just now.

If you have other commands you’d like to automate, you can simply replace what’s in either of these scripts with that command, save it as a new .sh file, make it executable, set it to open with Terminal, and you’re golden. For timed automation, you can even have these programs run with cron so that they’re executed for you on a regular schedule. How’s that for automation?

~Jonathan

Solving the Quadratic Equation with Fortran (With Complex Roots)

An interesting assignment given last semester was to write a program that returned the results of the Quadratic Equation to find the roots of a quadratic polynomial. What’s so interesting about that, you ask? The professor wanted the imaginary roots. In the end, it only took an “if” block to get it, but it did take some thought to get it right. At the time, this was one of my more proud moments as a programmer.

~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
! ---------------------------------------------------------
! Programmer:   Jonathan Landrum
! Date:         15 September 2011
! Class:        CSC 204
! ---------------------------------------------------------
! Program Name: quadraticEquation.exe
! Purpose:      Calculates the roots of a quadratic
!               equation, returning whether they are real
!               roots or imaginary roots.
! Assumptions:  1.) The input is in the form of a real
!                   number, not text. Text will cause the
!                   program to return an error.
! ---------------------------------------------------------
 
PROGRAM quadraticEquation
 
	IMPLICIT NONE
 
	! ------------------------------------------------------
	! Variables:
	! The response variable is a single character variable,
	! and input longer than one character will be truncated.
	! So technically, any word starting with the letter "y"
	! will keep the program running. Feature, not a bug(TM).
	! ------------------------------------------------------
	REAL		:: a, b, c, d = 0, fraction, radical
	CHARACTER	:: response
 
	! Introduce the program and ask for initial response
	WRITE (*,*) '*****************************************'
	WRITE (*,*) '*                                       *'
	WRITE (*,*) '* FORTRAN Quadratic Equation Calculator *'
	WRITE (*,*) '*                                       *'
	WRITE (*,*) '*****************************************'
	WRITE (*,*)
	WRITE (*,*) 'Copyright (c) 2011 Jonathan Landrum'
	WRITE (*,*)
	WRITE (*,*) 'This program calculates the roots of the'
	WRITE (*,*) 'quadratic equation, and returns whether'
	WRITE (*,*) 'the roots are real or imaginary.'
	WRITE (*,*)
	WRITE (*,*) 'The calculation is in the form:'
	WRITE (*,*) '(-B +/- (SQRT(B^2 - 4*A*C))'
	WRITE (*,*) '---------------------------'
	WRITE (*,*) '            2A'
	WRITE (*,*)
	WRITE (*,*) 'Do you want to continue? [Y/N]'
	WRITE (*,*)
 
	READ  (*,*) response ! Anything besides Y terminates
 
	! -----------------------------------------------------
	! Main Loop:
	! Keeps the user in the program until they choose to
	! close it.
	! -----------------------------------------------------
	WHILE ((response == 'Y') .OR. (response == 'y')) DO
 
		! -------------------------------------------------
		! Input Loop:
		! Takes in three real numbers for calculation.
		! -------------------------------------------------
		WRITE (*,*)
		WRITE (*,*) 'Enter a value for "A":'
		READ  (*,*) a
		WRITE (*,*) 'Enter a value for "B":'
		READ  (*,*) b
		WRITE (*,*) 'Enter a value for "C":'
		READ  (*,*) c
 
		! Discriminant = b^2 - 4*a*c
		d = b*b - 4*a*c
 
		! -------------------------------------------------
		! Computation Loop:
		! Determines if the discriminant is negative, and
		! computes the results.
		! -------------------------------------------------
		IF (d < 0) THEN
			fraction = -b/(2.0*a)
			radical  = (SQRT(ABS(d)))/(2.0*a)
			WRITE (*,*)
			WRITE (*,*) 'IMAGINARY ROOTS'
			WRITE (*,*)
			WRITE (*,*) fraction, ' + ', radical, 'i'
			WRITE (*,*) fraction, ' - ', radical, 'i'
		ELSE IF (d .EQ. 0) THEN
			WRITE (*,*)
			WRITE (*,*) 'REPEATED REAL ROOTS'
			WRITE (*,*)
			WRITE (*,*) -b/(2.0*a)
		ELSE
			WRITE (*,*)
			WRITE (*,*) 'REAL ROOTS'
			WRITE (*,*)
			WRITE (*,*) (-b + SQRT(d))/(2.0*a)
			WRITE (*,*) (-b - SQRT(d))/(2.0*a)
		END IF ! End computation Loop
 
		WRITE (*,*)
		WRITE (*,*) 'Do you want to convert another set of numbers? [Y/N]'
		WRITE (*,*)
		READ  (*,*) response ! Anything besides Y terminates
	END DO ! End Main Program Loop
 
	WRITE (*,*)
	WRITE (*,*) '\\//_ Live long and prosper.'
END PROGRAM quadraticEquation

Plotting Radioactive Decay with Fortran and ES-Plot

One of the assignments in Fortran last semester was to plot the exponential population growth of the United States between the years 1790 and 1860. Since I had recently taken Chemistry that summer, I also wrote a program to model the decay of the radioactive isotope Carbon-14, the isotope used in Radiocarbon Dating.

This program calculates the data, exports it to a CSV file, and finally calls the ES-Plot program and feeds it the CSV for data. An example output is below:

Decay model of the Carbon-14 isotope

In the graphic above, the vertical axis is number of moles present, and the horizontal axis is the number of years since the start of decay. It is difficult to read the numbers, but the first labeled tick mark is “1E+4”, 10,000 years. The average half-life of Carbon-14 is 5,730±40 years, not labeled here. The last tick mark is 40,000 years.

The user can input any quantity in moles for the program to calculate, but calculation will stop at 0.01% of the calculated mass because anything less than that is trivial in this case and is difficult to see in the resulting graphic. You will notice, therefore, that subsequent calculations result in the same graphic. That is because the decay rate of Carbon-14 is the same, regardless of quantity.

~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
! ----------------------------------------------------------
! Programmer:   Jonathan Landrum
! Date:         22 October 2011
! Class:        CSC 204
! ----------------------------------------------------------
! Program:      decay.f95
! Purpose:      Calculates and plots the radioactive decay
!               of Carbon-14. The half-life of Carbon-14 is
!               5,730 +/- 40 years. I have chosen 5,730 for
!               this model's lambda, as it is the mean.
! Assumptions:  1.) ES-Plot is installed.
!                   http://goo.gl/wmhZw
! ----------------------------------------------------------
 
PROGRAM decay
 
    IMPLICIT NONE
 
    CHARACTER                   :: response
    INTEGER                     :: t
    REAL                        :: p0, mass
    DOUBLE PRECISION, PARAMETER :: e = 2.71828182845904523536 !     ln 0.5
    DOUBLE PRECISION, PARAMETER :: k = -0.0001209680943385594 ! k = ------
                                                              !     lambda
 
    WRITE (*,*) '*******************************************'
    WRITE (*,*) '*                                         *'
    WRITE (*,*) '*FORTRAN CARBON RADIOACTIVE DECAY MODELLER*'
    WRITE (*,*) '*                                         *'
    WRITE (*,*) '*******************************************'
    WRITE (*,*)
    WRITE (*,*) 'Copyright (c) 2011 Jonathan Landrum'
    WRITE (*,*)
    WRITE (*,*) 'Calculates and plots the radioactive decay'
    WRITE (*,*) 'of Carbon-14 to the stable Nitrogen isotope'
    WRITE (*,*) 'Nitrogen-14, its most common isotope.'
    WRITE (*,*)
    WRITE (*,*) 'The half-life of Carbon-14 is 5,730 +/- 40'
    WRITE (*,*) 'years. I have chosen 5,730 for this model,'
    WRITE (*,*) 'as it is the mean.'
    WRITE (*,*)
    WRITE (*,*) 'Assumptions: 1.) ES-Plot is installed.'
    WRITE (*,*) '                 http://goo.gl/wmhZw'
    WRITE (*,*)
    WRITE (*,*) '------------------------------------------'
    WRITE (*,*)
    WRITE (*,*) 'Would you like to continue? [Y/N]'
    WRITE (*,*)
    READ  (*,*) response
    WRITE (*,*)
 
    ! Any response beginning with the letter "y" will work.
    WHILE (response == 'y' .OR. response == 'Y') DO
 
        WRITE  (*,*) 'How many moles of Carbon-14 do you want'
        WRITE  (*,*) 'to test?'
        WRITE  (*,*)
        READ   (*,*) p0
 
        t      = 0
        mass   = p0
 
        OPEN   (UNIT=8, FILE='decay.csv', status='unknown')
 
1       FORMAT (1X,I6,A2,F6.3)
 
        WRITE  (*,*) 'Year,   Mass'
        WRITE  (*,*) '------------'
        WRITE  (8,*) '$ Carbon-14 Decay Model'
 
        WHILE  (mass >= (p0 * 0.01)) DO
            mass  = (p0 * (e ** (k * t)))
            WRITE (8,*) t, ', ', mass
            WRITE (*,1) t, ', ', mass
            t     = t + 1
        END DO
 
        CLOSE  (8)
 
        WRITE  (*,*)
        WRITE  (*,*) '------------'
        WRITE  (*,*) 'End of list.'
        WRITE  (*,*)
        WRITE  (*,*) 'File "decay.csv" successfully created.'
        WRITE  (*,*) 'Calling ESPlot...'
 
        CALL SYSTEM ('"C:\Program Files (x86)\ESPlot\esplot.exe" decay.csv')
 
        WRITE  (*,*) 'Process Complete'
        WRITE  (*,*)
        WRITE  (*,*) '------------------------------------------'
        WRITE  (*,*) 'Would you calculate another mass? [Y/N]'
        WRITE  (*,*)
        READ   (*,*) response
        WRITE  (*,*)
    END DO ! Continue loop
    WRITE (*,*) '\\//_ Live long and prosper.'
END PROGRAM decay

Birthday Problem

In Probability and Stats last semester, my professor assigned us the project of determining how many students there would need to be in a class in order to have a 50/50 chance of having a repeat birth date. It’s called the Birthday Problem or Birthday Paradox. He mentioned that it’s quite a popular problem in probability classes, and that we cannot look online for the answer.

He wanted us to use our intuition to form a method for finding the answer. Obviously, since I’m a CS major, I turned to the computer for my answer. I was taking Fortran that same semester, so it was the freshest language on my mind. Any programming language would probably do, but I chose this one. A lot of what I’ve seen on the web with this problem is written in C or C++, so I feel I have a slight advantage here. ;~] Upon compiling and running the program, I came to my answer in less than one second: 23.

~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
! ---------------------------------------------------------
! Programmer:      Jonathan Landrum
! Date:            20 September 2011
! Class:           MAT 353
! ---------------------------------------------------------
! Program:         birthdays.exe
! Purpose:         Calculates the number of people you
!                  would need to question in order to have
!                  a 50% chance in getting two or more
!                  duplicate birth dates among the set.
! Assumptions:     None.
! ---------------------------------------------------------
 
PROGRAM BIRTHDAYS
	IMPLICIT NONE
 
	REAL      :: probability = 0.0, compliment = 1.0, days = 365
	INTEGER   :: counter = 1
	CHARACTER :: response
 
	WRITE (*,*) '******************************************'
	WRITE (*,*) '*                                        *'
	WRITE (*,*) '* FORTRAN DUPLICATE BIRTHDATE CALCULATOR *'
	WRITE (*,*) '*                                        *'
	WRITE (*,*) '******************************************'
	WRITE (*,*)
	WRITE (*,*) 'Calculates the number of people you would'
	WRITE (*,*) 'need to question in order to have a 50/50'
	WRITE (*,*) 'chance in having a duplicate birthdate.'
	WRITE (*,*)
	WRITE (*,*) 'This program takes no arguments from the'
	WRITE (*,*) 'user, except to continue after this line.'
	WRITE (*,*)
	WRITE (*,*) 'Would you like to continue? [Y/N]'
	WRITE (*,*)
	READ  (*,*) response
 
	! Any response beginning with the letter "y" will do.
	WHILE (response == 'y' .OR. response == 'Y') DO
 
		! -------------------------------------------------
		! Main:
		! This loop begins at 1 with the calculation and
		! continues until probability is greater than 50%.
		! -------------------------------------------------
		WHILE (probability < 0.51) DO
			compliment  = compliment * (days/365)
			probability = 1.0 - compliment
 
			WRITE (*,*) '| ', counter, ' | ', probability, ' |'
 
			counter = counter + 1
			days    = days - 1
		END DO ! Main loop
 
		WRITE (*,*)
		WRITE (*,*) 'Would you like to continue? [Y/N]'
		WRITE (*,*)
		READ  (*,*) response
	END DO ! Continue loop
	WRITE (*,*)
	WRITE (*,*) '\\//_ Live long and prosper.'
END PROGRAM BIRTHDAYS

Collatz Conjecture

I enjoy reading geeky webcomics. It’s one of my guilty pleasures. xkcd is my favorite, by far. A few weeks ago, I was perusing the xkcd store and found the Collatz Conjecture t-shirt (I’m also incredibly partial to geeky shirts.) I wasn’t familiar with the premise of this conjecture, so I hopped over to Wikipedia to see what it’s about.

According to the article, The Collatz Conjecture is the hypothesis that if you follow the algorithm presented, you will always end up at 1. The algorithm is to start with any natural number (a positive integer), and test it: if it’s odd, multiply your number by 3 and add 1; if it’s even, divide it by 2. Continue the algorithm indefinitely, and, according to the conjecture, you will always end up at 1.

That’s the idea, anyway. But it’s never been proven to be true. It’s assumed to be true, but not proven. (It hasn’t been proven because you cannot test every positive integer.) So it’s called a conjecture rather than a rule. And that’s where I started programming. I figured, hey, that’s easy. I’ll just write a program to prove it for me! Well, sort of. There’s an infinite set of positive integers, but a finite amount of memory in my computer. It will eventually run out of memory space on the machine. But it would still theoretically run forever on a perfect computer. What follows is no formal proof, but it’s about as close to a Q.E.D. as we will see for now in this problem. It starts with 2, proves that it goes to 1 (2 / 2 = 1), and then iterates to 3:

  1. 3 * 3 + 1 = 10
  2. 10 / 2 = 5
  3. 5 * 3 + 1 = 16
  4. 16 / 2 = 8
  5. 8 / 2 = 4
  6. 4 / 2 = 2
  7. 2 / 2 = 1

and so on. Now just to find a machine with infinite memory…

~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:         16 December 2011
// *****************************************************
// Program:      collatz.java
// Purpose:      Testing the Collatz Conjecture
// Assumptions:  None.
// *****************************************************
 
public class collatz {
 
	// ---------------------------------------------
	// main():
	// Does ALL the things
	// ---------------------------------------------
	public static void main (String[] args) {
 
		// -------------------------------------
		// Variables
		// -------------------------------------
		int n, in = 2, out = 1;
		Scanner scan = new Scanner(System.in);
 
		// -------------------------------------
		// Introduce the program
		// -------------------------------------
		System.out.println ("---------------------------");
		System.out.println ("-                         -");
		System.out.println ("- Collatz Conjecture Test -");
		System.out.println ("-                         -");
		System.out.println ("---------------------------");
		System.out.println ();
		System.out.println ("Takes the positive integers");
		System.out.println ("and tests them against the");
		System.out.println ("Collatz Conjecture.");
		System.out.println ();
 
		// -------------------------------------
		// Main block
		// -------------------------------------
		while (out == 1) {
			n = in;
			while (n > 1) {
				if (n%2 == 0) {
					n = n/2;
				} else {
					n = n * 3 + 1;
				} // End if
			} // End while
			out = n;
			System.out.println (in);
			in++;
		} // End while
	} // End main
} // End collatz

FizzBuzz

This article describes how I came to the realisation that I had to start JonLandrum.com.

I stumbled upon an article on Coding Horror the other day whilst perusing the web, and it made my stomach turn. Go read it, honestly. Right now. The premise of the article is there are people graduating from colleges and universities with degrees in Computer Science who can neither read nor write one single line of code.

And not just Associates or Bachelors, no. Full-fledged Masters and Doctorates who don’t know a lick of code, but they’ve earned the highest attainable degree in the field of computing. Granted, there’s definitely a philosophical side to Computer Science, and there are many Computer Science programs in academia that only focus on that end; it is, after all, a science. But if you, the applicant, are applying for a coding job, at least have the wit to familiarize yourself with the language first. If all you know is the science of computing and not the languages thereof, apply for one of those jobs instead.

To weed these codeless candidates out, hiring managers in many shops have taken to giving simple programming assignments to candidates. The one mentioned in the article above is called “FizzBuzz”. Here is my version, written in Java, that I whipped up in about five minutes. It is, quite literally, a Freshman’s problem. I won’t lie, I was a bit insulted at how easy the assignment is. I know you’re not supposed to post the answer. I understand that it’s not the point, that the point is we shouldn’t need FizzBuzz challenges. But I took that article as a personal affront. I had to prove myself, no matter how trivial the test.

“I am not one of them.”

There’s much more code to follow. FizzBuzz is just the beginning.

~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
// ****************************************************
// Programmer:           Jonathan Landrum
// Date:                 23 January 2012
// Class:                Comp. Sci. 101 (Seriously)
// ****************************************************
// Program:              FizzBuzz.java
// Purpose:              To prove that I can program.
// Assumptions:          A lot, apparently.
// ****************************************************
 
import java.util.Scanner;
 
public class FizzBuzz {
	public static void main (String[] args) {
 
		// --------------------------------------------
		// Variables
		// --------------------------------------------
		int	c = 1;
		String	response;
		Scanner scan = new Scanner(System.in);
 
		// --------------------------------------------
		// Introduce the program
		// --------------------------------------------
		System.out.println ("-------------------------------------");
		System.out.println ("-             Fizz Buzz             -");
		System.out.println ("-------------------------------------");
		System.out.println ();
		System.out.println ("This program reproduces a traditional");
		System.out.println ("British children's counting game, but");
		System.out.println ("more specifically, it represents a");
		System.out.println ("coding challenge.");
		System.out.println ();
		System.out.print   ("Would you like to continue? [Y/N] ");
 
			response   = scan.nextLine();
 
		// --------------------------------------------
		// Main block
		// --------------------------------------------
		while (response.charAt(0) == 'y' || response.charAt(0) == 'Y') {
			while (c <= 100) {
				if (c > 3) {
					if (c % 3 == 0 && c % 5 == 0) {
						System.out.println ("FizzBuzz");
					} else if (c % 3 == 0) {
						System.out.println ("Fizz");
					} else if (c % 5 == 0) {
						System.out.println ("Buzz");
					} else {
						System.out.println (c);
					} // End test if block
				} else {
					System.out.println (c);
				} // End print if block
				c++;
			} // End main while block
 
			System.out.println ("-------------------------------------");
			System.out.println ("Process complete.");
			System.out.print   ("Would you like to continue? [Y/N] ");
 
				response   = scan.nextLine();
 
		} // End while
		System.out.println ();
		System.out.println ("\\\\//_ Live long and prosper.");
		} // End main
} // End FizzBuzz