Skip to content

Instantly share code, notes, and snippets.

@ekopradesga
Last active February 18, 2020 01:34
Show Gist options
  • Save ekopradesga/407f2b91ffa42e368328bd1a6b59e83e to your computer and use it in GitHub Desktop.
Save ekopradesga/407f2b91ffa42e368328bd1a6b59e83e to your computer and use it in GitHub Desktop.
Quiz PHPID
public class Derivative {
private static String calculate(int n) {
if (n <= 1) return "";
StringBuilder res = new StringBuilder();
res.append(recX(n - 1, false));
res.append(recDX(n - 2));
return res.toString();
}
private static String recX(int n, boolean decrease) {
StringBuilder res = new StringBuilder();
if (n == 0) {
res.append("x");
return res.toString();
}
if (decrease) {
res.append("x^{");
res.append(recX(n - 1, false));
res.append("-1}");
return res.toString();
}
res.append("x^{");
res.append(recX(n - 1, false));
res.append("}");
return res.toString();
}
private static String recDX(int n) {
StringBuilder res = new StringBuilder();
if (n == 0) {
res.append("(\\ln(x)+1)");
return res.toString();
}
res.append("(");
res.append(recX(n, false));
res.append("\\ln(x)");
res.append(recDX(n - 1));
res.append("+");
res.append(recX(n, true));
res.append(")");
return res.toString();
}
public static void main(String []args){
System.out.println(calculate(4));
}
}
<?php
function derivative($n) {
$y = recX($n - 1);
$x = recDX($n - 2);
return sprintf("%s%s", $y, $x);
}
function recX($n, $decrease=false) {
if ($n == 0) return "x";
if ($decrease) {
$x = recX($n -1);
return sprintf("x^{%s-1}", $x);
}
$x = recX($n -1);
return sprintf("x^{%s}", $x);
}
function recDX($n) {
if ($n == 0) return "(ln(x)+1)";
$y = recx($n);
$ym = recX($n, true);
$dx = recDX($n - 1);
return sprintf("(%s\ln(x)%s+%s)", $y, $dx, $ym);
}
?>
def derivative(n):
y = recx(n - 1)
return '{} {}'.format(y, recdx(n - 2))
def recx(n, mi=False):
if n == 0:
return 'x'
if mi:
return 'x^{' + recx(n - 1) + ' - 1}'
return 'x^{{{0}}}'.format(recx(n - 1))
def recdx(n):
if n == 0:
return '(\ln(x) + 1)'
y = recx(n)
ym = recx(n, True)
return '({} \ln(x) {} + {})'.format(y, recdx(n - 1), ym)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment