This was part of my assignment and was asked to calculate factorial of 5 and 7.
I finished it as below:
import java.util.Scanner;
public class Factorial {
public static void main(String [] args)
{
System.out.println("Please enter a number: ");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
It worked for 5 and 7 (resulting 120 and 5040).
But my professor came over and test it with 20 and 987654321, result returns -2102132736 and 0.
Why is that?
P.S. I thought for the case of 987654321, the result would crush the application or return error since it would be huge.
This code can solve your problem . It is taken from here
class BigFactorial
{
static void factorial(int n)
{
int res[] = new int[300];
// Initialize result
res[0] = 1;
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
for (int x=2; x<=n; x++)
res_size = multiply(x, res, res_size);
System.out.println("Factorial of given number is: ");
for (int i=res_size-1; i>=0; i--)
System.out.print(res[i]);
}
// This function multiplies x with the number represented by res[].
// res_size is size of res[] or number of digits in the number represented
// by res[]. This function uses simple school mathematics for multiplication.
// This function may value of res_size and returns the new value of res_size
static int multiply(int x, int res[], int res_size)
{
int carry = 0; // Initialize carry
// One by one multiply n with individual digits of res[]
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod/10; // Put rest in carry
}
// Put carry in res and increase result size
while (carry!=0)
{
res[res_size] = carry%10;
carry = carry/10;
res_size++;
}
return res_size;
}
// Driver program
public static void main(String []args)
{
factorial(100);
}
}
Because 5040! is a very larger number (even long overflows). Use a BigInteger like
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= number; i++) { // <-- x * 1 = x
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of " + number + " is: " + fact);
This is because of the fact that the container that you have taken for storing and printing your result does not have the capacity to hold such big integer (I mean factorial of 20). So, you need a bigger container. As others already suggested, you can use BIGINTEGER.
Related
Fibonacci sequence is defined as a sequence of integers starting with 1 and 1, where each subsequent value is the sum of the preceding two I.e.
f(0) = 1
f(1) = 1
f(n) = f(n-1) + f(n-2) where n>=2
My goal is to calculate the sum of the first 100 even-values Fibonacci numbers.
So far I've found this code which works perfectly to calculate the sum of even numbers to 4million , however I'm unable to find edit the code so that it stops at the sum of the 100th value, rather than reaching 4million.
public class Improvement {
public static int Fibonacci(int j) {
/**
*
* Recursive took a long time so continued with iterative
*
* Complexity is n squared.. try to improve to just n
*
*/
int tmp;
int a = 2;
int b = 1;
int total = 0;
do {
if(isEven(a)) total +=a;
tmp = a + b;
b = a;
a = tmp;
} while (a < j);
return total;
}
private static boolean isEven(int a) {
return (a & 1) == 0;
}
public static void main(String[] args) {
// Notice there is no more loop here
System.out.println(Fibonacci(4_000_000));
}
}
Just to show the console from #mr1554 code answer, the first 100 even values are shown and then the sum of all is 4850741640 as can be seen below:
Any help is appreciated, thanks!
You need to use BigInteger because long easily overflows as Fibonacci's scales quite easily. BigInteger is also tricky to check whether is an odd or even number, but you can use BigInteger::testBit returning boolean as explained in this answer.
Here is some complete code:
BigInteger fibonacciSum(int count, boolean isOdd) {
int i = 0;
BigInteger sum = BigInteger.ZERO;
BigInteger current = BigInteger.ONE;
BigInteger next = BigInteger.ONE;
BigInteger temp;
while (i < count) {
temp = current;
current = current.add(next);
next = temp;
if ((current.testBit(0) && isOdd) || ((!current.testBit(0) && !isOdd))) {
sum = sum.add(current);
i++;
}
}
return sum;
}
Or you can have some fun with Stream API:
BigInteger fibonacciSum(int count, boolean isOdd) {
final BigInteger[] firstSecond = new BigInteger[] {BigInteger.ONE, BigInteger.ONE};
return Stream.iterate(
firstSecond,
num -> new BigInteger[] { num[1], num[0].add(num[1]) })
.filter(pair ->
(pair[1].testBit(0) && isOdd) ||
(!pair[1].testBit(0) && !isOdd))
.limit(count)
.map(pair -> pair[1])
.reduce(BigInteger.ZERO, BigInteger::add);
}
In any way, don't forget to test it out:
#Test
void test() {
assertThat(
fibonacciSum(100, false),
is(new BigInteger("290905784918002003245752779317049533129517076702883498623284700")));
}
You said.
My goal is to calculate the sum of the first 100 even-values Fibonacci numbers.
That number gets very large very quickly. You need to:
use BigInteger
use the mod function to determine if even
For this I could have started from (1,1) but it's only one term so ...
BigInteger m = BigInteger.ZERO;
BigInteger n = BigInteger.ONE;
BigInteger sumOfEven= BigInteger.ZERO;
int count = 0;
BigInteger t;
while( count < 100) {
t = n.add(m);
// check if even
if (t.mod(BigInteger.TWO).equals(BigInteger.ZERO)) {
sumOfEven = sumOfEven.add(t);
count++;
}
n = m;
m = t;
}
System.out.println(sumOfEven);
Prints
290905784918002003245752779317049533129517076702883498623284700
If, on the other hand, from your comment.
My aim is to calculate the sum of the first 100 even numbers
Then you can do that like so
sumFirstNeven = (((2N + 2)N)/2 = (N+1)N
so (101)100 = 10100 and the complexity is O(1)
as I figured, you want a program to sum 100 first even values of the Fibonacci series.
here is a sample code, when you run the program it will ask you to determine the number of the even values, you want 100 value e.g, type 100 in consul:
public static void main(String[] args) {
int firstNumber = 0;
int secondNumber = 2;
System.out.print("Enter the number of odd elements of the Fibonacci Series to sum : ");
Scanner scan = new Scanner(System.in);
int elementCount = scan.nextInt(); // number of even values you want
System.out.print(firstNumber + ", ");
System.out.print(secondNumber + ", ");
long sum = 2;
for (int i = 2; i < elementCount; i++) {
int nextNumber = firstNumber + secondNumber;
System.out.print(nextNumber + ", ");
sum += (nextNumber);
firstNumber = secondNumber;
secondNumber = nextNumber;
}
System.out.print("...");
System.out.println("\n" + "the sum of " + elementCount + " values of fibonacci series is: " + sum);
}
Working on a problem in which I take a user's input (1-10) and guess what number they are thinking of using binary search, and update the range dependent on their answer (e.g. if it is greater than 5, I update the lowerLimit to 6) but am having trouble with the logic.
I use the middle cell as reference by adding 1 to the middle cell when they say it is greater than it, but I believe this is where I get confused. I can't figure out how to intertwine my if/else statement to update the number correctly.
Main method:
public class Main {
public static void main(String[] args) {
// test your program here
GuessingGame game = new GuessingGame();
game.play(1,10);
}
}
GuessingGame method (play method is the one I'm working with):
import java.util.Scanner;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int LL, int UL) {
instructions(LL, UL);
int limit = howManyTimesHalvable(UL - LL);
int finalNumber = 0;
int midPoint = average(LL, UL);
int avgLL;
int avgUL;
for(int i = 0; i < limit; i++){
if(isGreaterThan(midPoint)){
midPoint++;
LL = midPoint;
midPoint = average(UL,LL);
finalNumber = LL;
}else{
midPoint--;
UL = midPoint;
midPoint = average(UL,LL);
finalNumber = LL;
}
if(UL == LL){
break;
}
}
System.out.println("Your number is : " + finalNumber);
}
public boolean isGreaterThan(int value){
System.out.println("Is your number greater than " + value + "?");
return reader.nextLine().equals("y");
}
public int average(int firstNumber, int secondNumber){
int total = firstNumber + secondNumber ;
return total / 2;
}
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
}
I would like to know how to update the ranges accordingly, when a user says that the number that they've guessed is higher or lower than what is shown to them.
Edit, example entries:
Looking for number 9,
LL: 1
UL: 10
limit:4
finalNumber:0
midPoint:5
i: 0
Is your number greater than 5?
y
LL: 6
UL: 10
limit:4
finalNumber:6
midPoint:8
i: 1
Is your number greater than 8?
LL: 9
UL: 10
limit:4
finalNumber:9
midPoint:9
i: 2
Is your number greater than 9?
n
LL: 9
UL: 8
limit:4
finalNumber:9
midPoint:8
i: 3
Is your number greater than 8?
y
Your number is : 9
You should not have midPoint--;
Since you are asking the question as "is Grater than"? Your new upper limit should be midpoint if the answer is no.
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 5 years ago.
I had a question in my exam. At first it was pretty easy. Let me explain the question:
Make the User Specify how many integers wants to put (Array)
Numbers should be between -1500 to 1500
(Tricky): Create a method that calculates the percentage of the numbers put, what percentage were 0, positive, negative.
(All this should be in ONE method, no return to string, string buffer, the return result should be a double value)
I think I did it right, but when I tested it in real time, the problem that I run is that it returns the values 0.0, 0.0, 0.0 ... Or it returns the correct percentage only if the values fall within the same condition (eg. all zero).
Here is my code: (I hope you can make sense out of it). I'm just curious, I don't know how to solve it. I have also tried it with a static method, I run into the same problem.
import java.util.Scanner;
public class nPNZ {
public int [] number;
public nPNZ (int [] n){
number = n;
}
public double [] allCalcs(){
int countPos = 0; int countNeg = 0; int countZero = 0;
for (int i = 0; i < number.length; i++) {
if (number[i] == 0) {
countZero++;
}else if (number[i] > 0){
countPos++;
}else{
countNeg++;
}
}
//0 = 0 ; 1 = positive ; 2 = negative
double total [] = new double [3];
total[0] = (countZero/number.length)*100;
total[1] = (countPos/number.length)*100;
total[2] = (countNeg/number.length)*100;
return total;
}
public static void main (String args[]){
//min 20 number, -1500 to 1500
Scanner input = new Scanner (System.in);
final int MIN_SIZE = 5;
int size = 0;
while(size < MIN_SIZE){
System.out.println("Specify the size of the array: ");
size = input.nextInt();
while(size<MIN_SIZE){
System.out.println("Size should be greater than: " + MIN_SIZE);
size = input.nextInt();
}
}
input.nextLine();
int num [] = new int [size];
for (int i = 0; i < num.length; i++) {
System.out.println("Write number " + (i+1) + " : ");
num[i] = input.nextInt();
while(num[i] < -1500 || num[i] > 1500) {
System.out.println("The number should within the range of -1500 and 1500");
num[i] = input.nextInt();
}
}
nPNZ n = new nPNZ (num);
System.out.println("Percentage of zero numbers is: " + n.allCalcs()[0] );
System.out.println("Percentage of positive numbers is: " + n.allCalcs()[1] );
System.out.println("Percentage of negative numbers is: " + n.allCalcs()[2]);
}
}
I can see one problem in your code.
double total [] = new double [3];
total[0] = (countZero/number.length)*100;
total[1] = (countPos/number.length)*100;
total[2] = (countNeg/number.length)*100;
return total;
Here, countZero, countPos and countNeg are all integers and number.length is also integer. So, when you divide an integer by another integer, you will get an integer.
Since, countZero, countPos and countNeg are all less than number.length, you will get zero value in the total array.
Example:
System.out.println(2/3); // prints 0
System.out.println(2.0/3); // prints 0.6666666666666666
System.out.println((double)2/3); // prints 0.6666666666666666
There are several alternatives to solve your problem. One of them is, simply multiply the integer by 1.0 while dividing it by another integer.
You can do something like this.
public double [] allCalcs(){
// your code goes here
double total [] = new double [3];
total[0] = (countZero * 1.0 / number.length) * 100;
total[1] = (countPos * 1.0 / number.length) * 100;
total[2] = (countNeg * 1.0 / number.length) * 100;
return total;
}
OR, you can declare the variables (countZero, countPos and countNeg) as double.
My question is why isn't the code generating the amount of numbers that the users enters? Right now the code is only generating one number. Here is the original question given to me:
"In your main method, prompt the user for a number n. Write a method
called assessRandomness that generates a random number between 1 and
100 'n' times and return the percentage of times the number was less than
or equal to 50. Call your assessRandomness method from main and display
the result to the user from main. Do not interact with the user from
within the assessRandomness method."
output:
How many random numbers should I generate? 10
<assume the random numbers generated were 11 7 50 61 52 3 92 100 81 66>
40% of the numbers were 50 or less
my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("how many random numbers should I generate?: ");
int number = in.nextInt();
assessRandomness(number);
}
public static double assessRandomness(int n){
int random = (int)(Math.random()*100);
int randomNumbersLessthan50 = 0;
if (random <= 50)
{
double getPercentage = random/randomNumbersLessthan50;
}
else
{
System.out.println(random);
}
return random;
}
I don't see any kind of loop within assessRandomness.
Try
for(int x = 1; x <= n; x++){ ... }
as first line in assessRandomness, it should finally look like
public static double assessRandomness(int n){
int counterLessThan50 = 0;
for ( int x = 1; x <= n; x++)
if( (int)(Math.random()*100) <= 50 ) counterLessThan50++;
return (double) counterLessThan50 / n;
}
There's no repetition in your code to do something n times.
Here's one way to do it in one line using a stream:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).map(r -> r * 100 + 1).filter(r -> r <= 50).count() / (double)n;
}
Note that converting Math.random() to a number in the range 1-100 is pointless; this will give the same result:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).filter(n -> n < .5).count() / (double)n;
}
And is easier to read.
At the moment, your assessRandomness method never uses the variable n.
At first you should initialize a variable which counts the number of created randoms that are bigger than 50 (this will be your retutn value). You should then do a loop from 0 until n. For each loop run you should create a random value between 0 and 100. Then you should check wether the value is bigger than 50. If so, count up your previously created variable. When the loop has finished, return the count variable and print it in the main method.
This should help you understand better how to do something like this.
public static void main(String[] args) {
System.out.println("how many random numbers should I generate?: ");
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int[] arrayPlaceHolderInMainMethod = new int[number];
arrayPlaceHolderInMainMethod = generateRandomNumberArray(number);
assessRandomness(arrayPlaceHolderInMainMethod);
}
public static void assessRandomness(int[] inputArray) {
int randomNumbersLessthan50 = 0;
int randomNumbersGreaterthan50 = 0;
int random = 0;
for (int i = 0; i < inputArray.length; i++) {
random = inputArray[i];
}
if (random <= 50) {
randomNumbersLessthan50 += 1;
} else {
randomNumbersGreaterthan50 += 1;
}
System.out.println(">50: " + randomNumbersGreaterthan50 + " Less: " + randomNumbersLessthan50);
}
public static int[] generateRandomNumberArray(int numberPickedByUser) {
int[] arrayOfRandomNumbers = new int[numberPickedByUser];
for (int i = 0; i < numberPickedByUser; i++) {
arrayOfRandomNumbers[i] = (int) (Math.random() * 100 + 1);
}
return arrayOfRandomNumbers;
}
I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */