Skip to content

Instantly share code, notes, and snippets.

@LESTADru
Last active January 4, 2016 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LESTADru/8630441 to your computer and use it in GitHub Desktop.
Save LESTADru/8630441 to your computer and use it in GitHub Desktop.
Решения SumTo(n); 3 способами.
<!DOCTYPE html>
<html>
<head>
<title>Рекурсия sumTo(n)</title>
</head>
<body>
<script>
var n;
//решение с помощью цикла.
function sumToCycle(n){
var sum = 0;
for(n;n>=1;n--){
sum += n;
}
return sum;
}
alert(sumToCycle(100));
// Решение с помощью рекурсии.
function sumTo(n){
return (n!=1 && n>1)? n+sumTo(n-1):n;
}
alert(sumTo(100));
// Решение с помощью математической формулы. S(n) = (A(1)+A(n))/2*n.
function sumToMath (n){
return (1+n)/2*n;
}
alert(sumToMath(100));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment