Project Euler > Problem 53 > Combinatoric selections (Java Solution)

Problem:

There are exactly ten ways of selecting three from five, 12345:

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

In combinatorics, we use the notation, 5C3 = 10.

In general,

nCr =
n!
r!(n[−]r)!
,where r [≤] n, n! = n[×](n[−]1)[×]...[×]3[×]2[×]1, and 0! = 1.

It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.

How many, not necessarily distinct, values of nCr, for 1 [≤] n [≤] 100, are greater than one-million?


Solution:

6857

Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
* Solution to Project Euler problem 3
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/


public final class p003 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p003().run());
}


/*
* Algorithm: Divide out all the smallest prime factors except the last one.
* For example, 1596 = 2 * 2 * 3 * 7 * 19. The algorithm ensures that the smallest factors will be found first.
* After dividing out the smallest factors, the last factor to be found will be equal to the quotient, so it must be the largest prime factor.
*/
public String run() {
long n = 600851475143L;
while (true) {
long p = smallestFactor(n);
if (p < n)
n /= p;
else
return Long.toString(n);
}
}


private static long smallestFactor(long n) {
for (long i = 2, end = Library.sqrt(n); i <= end; i++) {
if (n % i == 0)
return i;
}
return n; // Prime
}

}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact