Harmonic.java
public class Harmonic
{
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
double sum = 0.0;
for (int i = 1; i <= N; i++)
{
sum += 1.0 / i;
}
System.out.println(sum);
}
}
Sqrt.java
public class Sqrt
{
public static void main(String[] args)
{
double c = Double.parseDouble(args[0]);
double epsilon = 1e-15;
double t = c;
while (Math.abs(t - c/t) > epsilon*t)
{
t = (c/t + t) / 2.0;
}
System.out.println(t);
}
}
Binary.java
public class Binary
{
public static void main(String[] args)
{
int n = Integer.parseInt(args[0]);
int v = 1;
while (v <= n/2)
v = v * 2;
}
while (v > 0)
{
if (n < v)
{
System.out.println(0);
}
else
{
System.out.println(1);
n = n - v;
}
v = v / 2;
}
System.out.println();
}
}
Gambler.java
public class Gambler
{
public static void main(String[] args)
{
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]);
int T = Integer.parseInt(args[2]);
int bets = 0;
int wins = 0;
for (int t = 0; t < T; t++)
{
int cash = stake;
while (cash > 0 && cash < goal)
{
bets++;
if (Math.random() < 0.5) cash++;
else
cash--;
}
if (cash == goal) wins++;
}
System.out.println(wins + " wins of " + T);
System.out.println("Percent of games won = " + 100.0 * wins / T);
System.out.println("Avg # bets = " + 1.0 * bets / T);
}
}
No comments:
Post a Comment