How to represent a factorial programmatically [duplicate] - java

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.

Related

Trying to make a program that can pick out the top two numbers [duplicate]

This question already has answers here:
Printing the two highest values from user input
(4 answers)
Finding the two highest numbers based on input
(8 answers)
Closed 8 months ago.
import java.util.Scanner;
public class TopTwo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sequence of numbers: ");
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int first = Integer.MIN_VALUE;
int firstOccurences = 0;
int second = Integer.MAX_VALUE;
int secondOccurences = 0;
while(input.hasNextInt()){
int x = input.nextInt();
if(x > first){
first = x;
firstOccurences = 1;
}
else if (x == first){
firstOccurences += 1;
}
if(x>second){
second = x;
secondOccurences = 1;
}
else if(x<first){
secondOccurences += 1;
}
}
System.out.println("The highest is " + first + ". Its number of occurences is " + firstOccurences);
System.out.println("The second highest is " + second + ". Its number of occurrences is " + secondOccurences);
}
}
I'm trying to finish this code but I cannot figure out how to pick out the second highest number and could use some help, it can pick out the top value but not the second so far also it allows user input until anything besides a number is typed eg. fin .
Input: 24,56,62,12,79,-19,-12,-5,5,fin;
Output:The highest is 79. Its number of occurences is 1
The second highest is 2147483647. Its number of occurrences is 5.

Calculating a various number of facultys [duplicate]

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

Writing a very simple guessing game in Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Guess a number program with Java
(6 answers)
Closed 2 years ago.
I'm new to programming and while working on the Head First Java book I wanted to make a simple program, but there are some points I can't do. What I want the program to do is keep an integer number between 0 and 100 randomly and the user tries to find it. If the user finds the number, congratulations will appear on the screen. If not, it will ask for a new prediction. The code I wrote is below:
package Intro;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number: ");
int prediction = input.nextInt();
int number = (int) (Math.random());
if (number==prediction) {
System.out.println("Congratulations!");
}
else {
System.out.println("Wrong answer! Try a new number: ");
}
}
}
The point I stuck is that I can't make the randomly stored number integer and a number between 0 and 100. Another point is that if the answer is wrong, the program does not want a new prediction.
Very simple read this documentation on Random:
https://www.geeksforgeeks.org/java-math-random-method-examples/
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
int rand = (int)(Math.random() * range) + min;
// Output is different everytime this code is executed
System.out.println(rand);
}
Output:
6
8
10
10
5
3
6
10
4
2

Displaying 500 random integers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I want to generate 500 random numbers and display them next to their indexes. I want the numbers to be 1 though 10. But when I run my code it only generates 13 random numbers and the numbers are greater than 10. Please help.
public class RandomStats {
public static void main(String[] args) {
int [] stats = new int [501];
int numRolls;
int outcome;
for (int i = 0; i <=500; i++ ){
outcome = (int) ( 10 * Math.random() + 1)
+ (int) ( 10 * Math.random () + 1);
stats[outcome] += 1;
}
for ( int i = 2; i <=500; i++) {
System.out.println(i + ": " + stats[i]);
}
}
}
While saving in the array, you are doing stats[outcome] += 1;, where your array is updated with same index again and again and thats the reason you only see ~13 values and rest as 0. I believe it should be stats[i] =outcome+ 1;

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