PDA

View Full Version : Arithmetic/geometric progressions...


krycek
11-18-2002, 01:04 AM
I cannot remember the difference between arithmetic and geometric progressions... I did them in Further Maths a few years ago, but I forgot since (lol!)

I need to tell the computer to calculate n * n-1 * n-2 * n-3 etc. ... I am not sure if I am writing that correctly, but I want:

if n=5, then 5*4*3*2*1
if n=1473, then 1473*1472*1471*1470*... ...*5*4*3*2*1

I expect there is a better way to express that, but I do not know what it is (I forgot all except the easier maths since leaving college!)

I think that stuff is also tied in with nCr and nPr... does anyone know how I can do nCr and nPr in JS???

Cheers! :D

::] krycek [::

x_goose_x
11-18-2002, 01:26 AM
<script>
n = 10;
ans = 1;
for (x=1; x<=n; x++) {
ans *= x;
}
alert(ans);
</script>

krycek
11-18-2002, 01:36 AM
:) thanks goose, I guess that is the way I will have to do it then. I was hoping there was another way, like, built-in or summat.

::] krycek [::

jkd
11-18-2002, 02:46 AM
Factorial:

function factorial(n) {
return (n <= 0) ? 1 : n*factorial(n-1);
}


n Choose r:

function choose(n, k) {
var min, max;
var numerator = 1;
if (n == 0)
return 0;
if (k > n-k) {
max = k;
min = n-k;
}
else {
max = n-k;
min = k;
}
for (; n > max; n--)
numerator *= n;
return numerator / factorial(min);
}


n Permute r:

function permute(n, k) {
var response = 1;
var cancel = n - k;
for (; n > cancel; n--)
response *= n;
return response;
}


Something like that should work. Choose and Permute have some optimizations to avoid overflow in some situations.

krycek
11-18-2002, 01:33 PM
Wow... thanks! That's exactly what I was looking for :)

As I guess you are a maths whizz ;) could you also take a look at this thread for me?

http://www.codingforums.com/showthread.php?s=&postid=48282#post48282

I am struggling there also.

Cheers! :D

::] krycek [::