Calculating a various number of facultys [duplicate] - java

This question already has answers here:
Is there a method that calculates a factorial in Java? [closed]
(30 answers)
Closed 11 months ago.
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);
}
}
}

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);
}

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

Related

Alternate between operations in a for-loop

I'm a Java beginner, please bear with me. :) I haven't learned anything like if statements and such yet, I've only learned about loops, variables, and classes. I need to write a single loop which produces the following output:
10 0 9 1 8 2 7 3 6 4 5 5
I can see from the segment, that the difference between the numbers is reduced by one, so from 10 to 0 it is subtracted 10, then from 0 to 9 it is added by 9, and it goes on alternating between adding and subtracting.
My idea was to create the loop where my variable i = 10 decreases by 1 in the loop (i--) but I'm not quite sure how to alternate between adding and subtracting in the loop?
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
System.out.print(i + " ");
}
}
}
Why not have two extra variables and the increment one and decremented the other:
int y = 0;
int z = 10;
for(int i = 10; i >= 5; i--) {
System.out.print(z + " " + y + " ");
y++;
z--;
}
Output:
10 0 9 1 8 2 7 3 6 4 5 5
However we can also do this without extra variables:
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + 10-i + " ");
}
I don't think the OP actually wanted somebody to do their homework for them, so I'm gonna stick to answering the question they actually asked: how to alternate between two operations within a loop (so they can keep the algorithm they came up with :)).
There's a nifty "trick" that's very often used when we want to do something every other iteration in most programming languages. You'll most definitely come across it in your life, and it could be perplexing if you've got no clue what's going on, so here it goes!
The modulo (%) operator will yield the remainder of the division between its operands.
For instance, consider the following: 7 ÷ 2 = 3.5
When working for integers, you'd say that 7 ÷ 2 = 3, then you're left with 1.
In this case, when all variables are ints, in Java, 7 / 2 would be 3 and 7 % 2 is 1.
That's modulo for you!
What's interesting about this operator is inherent to what's interesting about division in general, and one case in particular: the remainder of a division by 2 is always either 0 or 1... and it alternates! That's the key word here.
Here comes the "trick" (not really a trick, it's basically a pattern considering how widely used it is) to alternating operations over iterations:
take any variable that is incremented every iteration in a loop
test for the remainder of the division of that variable by 2
if it's 0, do something, otherwise (it'll be 1), take the alternate path!
In your case, to answer your actual question (although others do have good points, I"m not trying to take that away from anybody), you could consider using something like that:
if( i % 2 == 0 ) {
// i is even, subtract
} else {
// i is odd, add
}
That'd allow you to keep going with the algorithm you initially thought of!
public class exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; i--) {
System.out.print(i + " " + (10-i) + " ");
}
}
}
Or you can do it this way, if you want to be a wiseass ;)
for(int i = 0, arr[] = {10,0,9,1,8,2,7,3,6,4,5,5}; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
This looks a bit like a homework assignment, so I won't give you working code.
But remember that you can put multiple print statements inside the for loop. You don't necessarily have to iterate 10 times to get your output. 5 times is totally enough. And as already stated in a comment above: the numbers alternate between i and 10-i, for the right range of i.
replace i >= 0 with i >= 5
add this : System.out.print((10-i--) + " ");
starting from what you did
public class Exercise7 {
public static void main(String[] args) {
for(int i = 10; i >= 5; ) {
System.out.print(i + " " + (10-i--) + " ");
}
}
}
Somethings don't need overthinking:
public class Answer2 {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++){
System.out.println(i);
System.out.println(10 - i);
}
}
}
edit
You CAN and should generalize your task. Here is an example how you could do it (I won't write the method, since it's your job - instead I'll alter my answer just to show you the possibilities)
public class Answer2 {
private static final Random RANDOM = new Random();
public static void main(String[] args) {
//You can use any upper bound for 'someLength'
int someLength = 1 + RANDOM.nextInt(20);
for (int i = 0; i <= someLength / 2; i++) {
System.out.println(someLength - i);
System.out.println(i);
}
}
}
Who said that you can only use one System.out.print in the loop?
for (int i=0; i < 5; i++) {
System.out.print((10 - i) + " " + (i + 1) + " ");
}
You should think about generalizing the series. As you have observed, the series alternates between addition and subtraction. Also, the difference goes down by one at each step. You can define variables for these two and adjust them in the loop.
public static void main(String[] args) {
int term = 10;
int sign = 1;
for(int delta = 10; delta >= -1; delta--) {
System.out.print(term + " ");
sign = -1 * sign;
term = term + sign * delta;
}
}
Simply run a loop either starting from 0 or starting from 10.
1.
If you start from 10
for(int i=10;i>=5;i--){
System.out.print(i + " " + (10-i) + " ");
}
2.
If you start from 0
for(int i=0;i<=5;i++){
System.out.print((10-i) + " " + i + " ");
}
The output will be:
10 0 9 1 8 2 7 3 6 4 5 5
I tried this code. It worked for me.
for(int i = 10; i >= 5; i--) {
System.out.print(i + " ");
System.out.print(10-i + " ");
}
This is here. The output list is a list of combinations to make 10;
10 0 9 1 8 2 7 3 6 4 5 5
10 + 0 = 10
9 + 1 = 10
8 + 2 = 10
7 + 3 = 10
6 + 4 = 10
5 + 5 = 10
int n = 10;
int half = n / 2;
if(n % 2 == 1){
half++;
}
for(int x = n; x >= half;x--){
int remainder = n % x;
if(remainder == 0){
remainder = n - x;
}
System.out.print(x);
System.out.print(" ");
System.out.println(remainder);
}

How to represent a factorial programmatically [duplicate]

This question already has answers here:
print factorial calculation process in java
(3 answers)
Java factorial format
(2 answers)
How do I calculate factorial and show working?
(2 answers)
Closed 4 years ago.
I couldn't find a proper title.
I wrote a tiny program to calculate the factorial of a given integer. The program works fine as expected. Now I would like to also print its representation, say we have 4 as input, the program would output 24 and then print Because 4! = 4 x 3 x 2 x 1.
public class Test {
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
int i;
int fact;
int number= sc.nextInt();//Get user input and calculate its factorial
fact = factorial(number);
System.out.println("Factorial of " + number + " is " + fact);
System.out.println("Because " + number+"!" + " = " + number + "x" + (number - 1) ); // This is what I tried so far
}
}
The last println shows what I have tried. However, I'm only able to output 4! = 4 x 3, unable to go down to 1.

Java aliquant number [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 4 years ago.
I am practicing a question: Type several numbers and stops while you type 0. Print out the maximum, minimum and average of the numbers you type.
Following is my code, and I was stuck in the calculation of average.
For example: when I type: 2 5 7 -1 0
the outcome is :
Type some numbers, and type 0 to end the calculattion:
2 5 7 -1 0
The numbers you type are:
2 5 7 -1
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.0
However, the Average should be 3.25.
I've already made the variable avg in double type, why my output is still 3.0 rather than 3.25?
Thanks!!
public class Max_Min_Avg {
public static void main(String[] args) {
System.out.println("Type some numbers, and type 0 to end the calculattion: ");
Scanner scanner = new Scanner(System.in);
int numbs = scanner.nextInt();
int count =0;
int sum =0;
int max = 0;
int min=0;
System.out.println("The numbers you type are: ");
while(numbs!=0) {
System.out.print(numbs + " ");
sum += numbs;
count ++;
numbs = scanner.nextInt();
if(numbs>max) {
max = numbs;
}
if(numbs<min) {
min = numbs;
}
}
while(numbs ==0) {
break;
}
System.out.println();
double avg = (sum/count);
System.out.println("Sum is: "+ sum);
System.out.println("There are "+ count + " numbers");
System.out.println("The Max number is : " + max );
System.out.println("The minimum number is : " + min);
System.out.println("Average is : " + avg);
}
This is the issue of integer division .sum/count is calculated as int since sum and count is of type int. You can solve this by implicit casting.
Try :-
double avg = sum*1.0/count; // implicit casting.
Output :-
Type some numbers, and type 0 to end the calculattion:
2 5 7 -1 0
The numbers you type are:
2 5 7 -1
Sum is: 13
There are 4 numbers
The Max number is : 7
The minimum number is : -1
Average is : 3.25

Duplicating prime numbers of even numbers

This part of an assignment requires to check every even number in an array for 2 prime numbers that add up to that even number. I already managed to find all the primes between 2 and each even number and put those primes in a separate array list. I've already found how to find 2 prime numbers that add up to each even number; however when I check the output, it gives me multiple answers like this:
How many numbers would you like to compute:
12
Your two prime factors that add up to 4 are:
2 & 2
Your two prime factors that add up to 6 are:
3 & 3
Your two prime factors that add up to 8 are:
3 & 5
Your two prime factors that add up to 8 are:
5 & 3
Your two prime factors that add up to 10 are:
3 & 7
Your two prime factors that add up to 10 are:
5 & 5
Your two prime factors that add up to 12 are:
5 & 7
Your two prime factors that add up to 12 are:
7 & 5
All I want is ONE pair of primes that sum up to each even number in a loop. My code looks like this:
//For Loop looks at every even number in the arrayList
//for(int c = 0; c < len; c++) {
//Code for Numbers that come before every even number
//Code for Finding primes
//Finding prime numbers that add up to even number
int len3 = primeNumbers.size();
for(int f = 0; f < len3; f++) {
if(primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
break;
}
for(int g = 1; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
break;
}
}
}
}
Try this. Your second loop should start from f. So if you do that u can remove the first if you have and then have this. I havent tested it. But try and let me know if it works.
for(int f = 0; f < len3; f++) {
for(int g = f; g < len3; g++) {
if(primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
}
}
}
When you call break statement it simply break current loop if your method only handle this logic simply change break statement to return. Hope this is you expect :
int len3 = primeNumbers.size();
for (int f = 0; f < len3; f++) {
if (primeNumbers.get(f) + primeNumbers.get(f) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(f));
return;
}
for (int g = 1; g < len3; g++) {
if (primeNumbers.get(f) + primeNumbers.get(g) == index) {
System.out.println("Your two prime factors that add up to " + index + " are: ");
System.out.println(primeNumbers.get(f) + " & " + primeNumbers.get(g));
return;
}
}
}

for Loop in Java - exponents

Basically, there is a group of 20 sheep. After the group has grown to a population of 80 sheep, the group does not need to be supervised anymore. The number of sheep, N, each year, t, is found with :
N = 220/(1 + 10(0.83)^t)
This program tries to find out how many years the sheep have to be supervised and writes out the value of N for t starting at zero and going up to 25.
This is my code so far...it doesn't seem to work and I know there is something to do with the part about multiplying with the power. I'm trying to use a variable "power" that is multiplied by 0.83 in each iteration of the loop. Any help is appreciated, thank you.
public static void main(String[] args) {
System.out.println("A breeding group of 20 bighorn sheep is released in a protected area in Colorado.");
System.out.println("After the group has reached a size of 80 sheep, the group does not need to be supervised anymore.");
System.out.println("This program calculates how many years the sheep have to be supervised.");
int number = 20;
int power = 1;
for(int years = 0; number < 80; power*= 0.83) {
number = 220 / (1 + 10 * power);
System.out.println("After " + years + " years, the number of sheep is: " + number);
years++;
}
}
}
change your data types on number and power from int to double. I tried it and it runs correctly. You also might want to modify your for loop to run while years < 25 rather than number < 80. And make number a local variable inside the loop for cleanliness.
public static void main(String[] args) {
System.out.println("A breeding group of 20 bighorn sheep is released in a protected area in Colorado.");
System.out.println("After the group has reached a size of 80 sheep, the group does not need to be supervised anymore.");
System.out.println("This program calculates how many years the sheep have to be supervised.");
double power = 1;
boolean foundFirstOverEighty = false;
for (int years = 0; years < 25; years++) {
double number = 220 / (1 + 10 * power);
System.out.println("After " + years + " years, the number of sheep is: " + number);
if (!foundFirstOverEighty && number >= 80) {
System.out.println("First time number of sheep exceeded eighty. " + years + " years. number of sheep is: " + number);
foundFirstOverEighty = true;
}
power *= 0.83;
}
}

Categories

Resources