Thursday 15 July 2010

Algorithm for binomial coefficient (nCr) in Ruby -


I have been given the task to solve this problem:

Actually ten Methods of selecting three to three, 12345:

  123, 124, 125, 134, 135, 145, 234, 235, 245 and 345   

5C3 = 10 . In general,

  nCr = n! / R! (NA)!   

Where r ?? ¤ n , n! = NÃ ?? (Nâ ???? 1) one ?? ... One ?? 3Ã ?? 2Ã ?? 1 , and 0! = 1 .

It is not up to n = 23 , this value is more than one million: 23C10 = 1144066 .

How many, not necessarily different, the value of nCr , for 1 ?? ¤ n â ?? ¤ 100 , is more than a million?

I have to come up with an algorithm in Ruby to solve that problem, but I do not understand how it happened.

This is a project Euler problem. You have to implement Pascal's triangle to solve this problem. . The Pascal triangle is symmetric, so we have to calculate half to get results, this will help your program run faster.

@@ fact_table = [] @@ Fact_table [0] Another method is that you can cache the factual results already calculated and use them to avoid unnecessary calculation overload can do. = 1; @@ fact_table [1] = 1; I in (2..100) @@ fact_ table [i] = i * @@ fact_ table [i-1] end DEP NCR (N, R) returns @@ fat_table [n] / (@@ fat_table [r] * @ @Fact_Table [NR]) for N = 0 (1. 1.00) for R (1.n) if NCR (N, R) & gt; 1000000 points + = 1 end and print "Count:", number, "\ n"

output

  Count of more than 1 million: 4075    

No comments:

Post a Comment