Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Kougami en 6 Octubre 2017, 17:52 pm



Título: Factorial
Publicado por: Kougami en 6 Octubre 2017, 17:52 pm
Buenas, tengo un problema con el siguiente codigo:

Código
  1. package factorial;
  2.  
  3. public class Factorial {
  4.  
  5. public static int factorial (int n) {
  6. int fact = 1;
  7. if (n < 0) {
  8. fact = 0;
  9. }
  10. else if ( n == 0){
  11. fact = 1;
  12. }
  13. else {
  14. fact = fact * n;
  15. }
  16. return fact;
  17. }
  18.  
  19. public static int combinatorio (int n, int k) {
  20. int combi = factorial (n) / (factorial(k) * factorial(n-k));
  21. return combi;
  22. }
  23.  
  24. public static void main(java.lang.String[] args) {
  25. for (int i = 0; i < 6; ++i) {
  26. for (int j = 0; j <= i; ++j)
  27. System.out.print(Factorial.combinatorio(i,j) + " ");
  28. System.out.println();
  29. }
  30. }
  31. }
  32.  

La salida deberia ser:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Pero sin embargo me sale:
1
1 1
1 2 1
1 1 1 1
1 1 1 1 1
1 1 0 0 1 1

Para compilar y ejecutar estoy usando el Eclipse 4.4 sobre java 1.8.0
Muchas gracias de antemano


Título: Re: Factorial
Publicado por: ivancea96 en 6 Octubre 2017, 21:54 pm
Ve por partes. Primero, asegurate de que cada función realiza su cometido correctamente.
¿La función factorial lo calcula correctamente?
Para n=5, el factorial lo estás calculando así: fact = 1(fact) * 5(n) -> 5.