start c++ implementation

This commit is contained in:
Ben Harris 2016-09-04 14:17:30 -04:00
parent 75509d217a
commit 4591ba1222
8 changed files with 134 additions and 79 deletions

17
cpp_src/Makefile Normal file
View File

@ -0,0 +1,17 @@
CSW = -O3 -Wall
LSW = -lfd
all:
make collatz
collatz: collatz.o Makefile
g++ collatz.o -o collatz
collatz.o: collatz.cc Makefile
g++ collatz.cc -c -o collatz.o $(CSW)
collatz.cc: collatz.h Makefile
touch collatz.cc
clean:
touch Makefile; make

BIN
cpp_src/collatz Normal file

Binary file not shown.

View File

@ -1,12 +1,38 @@
// Ben Harris
#import <unistd.h>
#import <cstdlib>
#import <string>
#import <iostream>
#import "collatz.h"
using namespace std;
int *prev = new int[1000000];
int maxcnt = 0, maxsteps = 0;
int main (int argc, char **argv) {
cout << "cCollatz" << endl;
for (int i = 1; i <= 100000; i++) {
cout << i << "\tnum of steps: " << collatz(i) << endl;
}
cout << "Longest path was " << maxsteps << " steps for " << maxcnt << endl;
}
int collatz (int start) {
int cnt = 0;
int initval = start;
while(start != 1) {
cnt++;
if (start < 1000000 && prev[start] != 0) {
start = prev[start];
continue;
}
start = start % 2 == 0 ? start/2 : 3*start + 1;
}
prev[start] = cnt;
if (cnt > maxcnt) {
maxcnt = initval;
maxsteps = cnt;
}
return cnt;
}

10
cpp_src/collatz.h Normal file
View File

@ -0,0 +1,10 @@
// Ben Harris
#ifndef _COLLATZ_h_
#define _COLLATZ_h_
// method definitions
int main(int argc, char **argv);
int collatz(int start);
#endif

BIN
cpp_src/collatz.o Normal file

Binary file not shown.

View File

@ -1,3 +1,5 @@
// Ben Harris
class Collatz {
int prev[] = new int[1000000];
@ -5,7 +7,7 @@ class Collatz {
int maxsteps = 0;
public static void main(String[] args) {
System.out.println("collatz calc");
System.out.println("javaCollatz");
Collatz c = new Collatz();