Last active
January 4, 2016 13:49
-
-
Save LESTADru/8630441 to your computer and use it in GitHub Desktop.
Решения SumTo(n); 3 способами.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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