0

im trying to implement a way to calculate facultys with for loops for a university project. I wrote a for loop that increases in steps of two, while another for loop calculates each faculty for the first for loop.

Can anybody point out where i made a mistake?

package Cosinus;

public class MainCos {
     public static void main(String[] args) { 
         
         
         int fact=1;
        for(int number = 0; number <= 10; number += 2) {
              for(int i=1;i<=number;i++){
              fact=fact*i;
         }
         System.out.println("The Faculty of " + number + " is: " + fact);
        }
    }
}        
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

2 Answers2

1

I know it is hard for the first time, to figure factorial out, but basically, you need to multiply each number by the next integer so on. There are many ways to solve it, one way you can create a method either recursively or iteratively. I would prefer iterator here a for loop perhaps.

n! factorial You can also say it is n! or n factorial in general. now S = 5! 1 * 2 * 3 * 4 * 5 = 120 in decimal.

        long fact = 1;
        for (long count = 2; count <= 10; count++) {
            fact = fact * count;
            System.out.println("The Faculty of " + count + " is: " + fact);
        }

Justin
  • 177
  • 8
1

If you're trying to compute the factorial of the even numbers, then just move int fact=1; to between the for loops so that it gets reset for each new number:

for(int number = 0; number <= 10; number += 2) {
  int fact=1;
  for(int i=1;i<=number;i++){
    fact=fact*i;
   }
   System.out.println("The Faculty of " + number + " is: " + fact);
}

Output:

The Faculty of 0 is: 1
The Faculty of 2 is: 2
The Faculty of 4 is: 24
The Faculty of 6 is: 720
The Faculty of 8 is: 40320
The Faculty of 10 is: 3628800

As others have pointed out, though, there is no need for nested loops here. Another approach would be to use just the outer loop, incrementing by one, and only display the factorial for even numbers. I've also added in the base condition of 0! = 1 :

int fact=0;
for(int number = 0; number <= 10; number++) {
  if (number == 0) {
    fact = 1; // by definition
  }
  else {
    fact = fact * number;  
  }
  if (number % 2 == 0) {
    System.out.println("The Faculty of " + number + " is: " + fact);
  }
}

Producing the same output:

The Faculty of 0 is: 1
The Faculty of 2 is: 2
The Faculty of 4 is: 24
The Faculty of 6 is: 720
The Faculty of 8 is: 40320
The Faculty of 10 is: 3628800
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40