import java.util.*; public class GreedyAlgorithm { public static void main(String[] args) { Sqrt s = new Sqrt(5); GreedyAlgorithm.run(s); } public static void run(Solution sNow) { int stayCount = 0; while (stayCount < 100) { if (sNow.improve()) { stayCount = 0; System.out.println(sNow.toString()); } else stayCount++; } } } interface Solution { boolean improve(); } class Sqrt implements Solution { double now = 0.0, y = 5.0; Random random = new Random(); public Sqrt(double py) { y = py;} public boolean improve() { double next = now+random.nextDouble()/100; if (score(next) > score(now)) { now = next; return true; } return false; } double score(double v) { return -Math.abs(v*v-y); } public String toString() { return "square("+now+")="+(now*now); } }