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
What I need to do is make a number generator that stops when it generates 10 and shows how many attempts there was until 10 was reached. I also have to use only while loops for this. Here's my code now:
public static int RandomOccurrence()
{
int randNumber = (int)(Math.random()*20 + 1);
int count = 0;
while(randNumber != 11){
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
and here's the function call:
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
But when I run the code it prints "the number generated is 2" infinitely.
Here's a fixed version of your code, which mostly involves moving the line that gets a random number into the while loop:
public static int RandomOccurrence()
{
int randNumber = 0;
int count = 0;
while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
randNumber = (int)(Math.random()*20 + 1);//added
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
System.out.println(RandomOccurrence());
Sample result:
The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5
I really prefer to point the user towards the answers for homework problems instead of giving them code that works. Because we're trying to "teach a man to fish."
The problem with the original code is that it must generate another random number within the while loop. The simplest way to do this is to copy-and-paste the same function-call that you used to generate the first one.
P.S.: You'll very quickly now see that "there's more than one way to do it!"
you should update your random number every time the while loop gets executed:
So randNumber = (int)(Math.random()*20 + 1); should be inside the loop
public static int RandomOccurrence(){
int count = 0;
int randNumber = 0;
while(randNumber != 11){
randNumber = (int)(Math.random()*20 + 1);
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
public static void main(String...args){
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
}
I hope I could help
Here's a 1-liner:
long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
.takeWhile(i -> i != 11).count();
See live demo.
∑i=1n1i
In other words, the method should generate the following sequence:
1+12+13+14+15+⋯
I've been stumped on this problem for quite a bit. Having a tough time understand what "n" stands for in the equation and applying it to my for loop.
Would a for loop be optimal for solving this? Or should I just use a formula and somehow solve it then?
public static void main(String[] args) {
//Chapter 4 Exercise 1
System.out.println("--Chapter 4, Exercise 1");
System.out.println("How many integers do you want?:");
Scanner console = new Scanner(System.in);
int numb = console.nextInt();
fractionSum(numb)
public static double fractionSum(int numb) {
for(int i = 1; i <numb; i++) {
if (i !=1)
System.out.print("1 + 1" + i);
else
System.out.print("1");
}
return(numb);
}
1+12+13+14+15+⋯
Should be the output.
My output is coming out as:
11 + 121 + 131 + 141 + 15
Answering the first part of your question:
∑i=1n1i is known as the Harmonic Sum - the output you give in your question is wrong, harmonic sum can be described as the sum of reciprocals of the positive integers - for example:
H1 = 1
H2 = 1 + 1/2 = 1.5
H3 = 1 + 1/2 + 1/3 = 1.8333
H4 = 1 + 1/2 + 1/3 + 1/4 = 2.0833
H(n) = 1 + 1/2 + 1/3 + 1/4 ... + 1/n = answer ---> see what n is now?
You should use a for-loop for this, and its not very complex. Hopefully, this answer will clear up the task for you (I assume homework from Chapter 4 Exercise 1) and you can try again.
Here:
class Harmonic {
public static void main(String… s) {
int n, i;
float sum = 0;
n = Integer.parseInt(s[0]);
for (i = 1; i <= n; i++) {
sum = sum + (float) 1 / i;
}
System.out.println(“nSum = ”+sum);
}
}
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);
}
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.