Tuesday, October 11, 2011

Code from our exam review

Hi Everyone! Here's code we worked on on Tuesday (10/11). Here's the Nth Prime puzzle:
public class Primes {
public static void main(String[] args) {
int n = 34;
int count = 0;
// for (int k=2; ; k++) {
int k = 2;
while (true) {
boolean isPrime = true;
// for (int j=2; j<k; j++) {
int j = 2;
while (j < k) {
if (k % j != 0) {
}
else {
isPrime = false;
break;
}
j++;
}
if (isPrime) {
count++;
}
if (count == n) {
System.out.println(k);
return;
}
k++;
}
}
}
view raw Primes.java hosted with ❤ by GitHub
Here's the 7s puzzle:
public class Sevens {
public static void main(String[] args) {
int min = 1;
int max = 100;
int seven = 0;
for (int k=min; k<=max; k++) {
if ((k / 1) % 10 == 7) {
seven++;
}
if ((k / 10) % 10 == 7) {
seven++;
}
if ((k / 100) % 10 == 7) {
seven++;
}
if ((k / 1000) % 10 == 7) {
seven++;
}
if ((k / 10000) % 10 == 7) {
seven++;
}
}
System.out.println(seven);
}
}
view raw Sevens.java hosted with ❤ by GitHub
Here's the highest-lowest puzzle:
public class SmLr {
public static void main(String[] args) {
int stop = IO.readInt();
int input = IO.readInt();
int highest = input;
int lowest = input;
while (input != stop) {
if (input > highest) {
highest = input;
}
if (input < lowest) {
lowest = input;
}
input = IO.readInt();
}
System.out.println(lowest);
System.out.println(highest);
}
}
view raw SmLr.java hosted with ❤ by GitHub
You're probably forgotten all about this by now, but here's that timing puzzle we did the week before. It doesn't quite work yet... but it's sooo close:
public class Time {
public static void main(String[] args) {
long now = System.currentTimeMillis();
int count = 0;
while (System.currentTimeMillis() - now <= 100) {
Math.sin(2);
count++;
}
long after = System.currentTimeMillis();
long diff = after - now;
System.out.println(diff / count);
}
}
view raw Time.java hosted with ❤ by GitHub
And then there's that 3n+1 puzzle:
public class Collatz {
public static void main(String[] args) {
int n;
int count = 0;
int highest = 0;
int k = 1;
for ( int i = 1; i<=100 ; i++) {
n = i;
count = 0;
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
//System.out.println(n);
}
else {
n = n * 3 +1;
//System.out.println(n);
}
count++;
}
if (count > highest) {
highest = count;
k = i;
}
//System.out.println(count);
}
System.out.println(k);
System.out.println(highest);
}
}
view raw Collatz.java hosted with ❤ by GitHub
Everyone, good luck on the exam!! I hope it goes wonderfully. If you have any questions or concerns or opinions or rants or hopes or dreams you can email me. Or if there's some code I forgot to put up here that you'd like to see. See you next week!

No comments:

Post a Comment