Using loops to compute factorial numbers, Java - java

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. */

Related

How to print each number of a given number separately?

I have a code is written that is supposed to print each of the numbers separately. Heres an example.
printDigits(1362) prints
2
6
3
1
printsDigits(985) prints
5
8
9
You can pull apart a number into its digits using / 10 and % 10.
I have started some code the way I was taught but I am not sure what to do with the other variables.
Please have a look:
public class Main {
public static void main(String[] args) {
System.out.println(printDigits(1362));
System.out.println(printDigits(985));
}
public static int printDigits(int x){
int y = x % 10;
while (x > 0){
x = y;
System.out.println(x);
x = x / 10;
}
return x;
}
}
Why don't you convert the parameter x to String then read each Char in the String since a String is array of Char. If the output must be an int you convert the Char to int.
printDigits method should be like this:
public static void printDigits(int x) {
int y;
while (x > 0) {
y = x % 10;
System.out.println(y);
x = x / 10;
}
}
And the calling of the method will be like this:
printDigits(1362); // without the System.out.println()
There are various ways to achieve such results. You can better understand all solutions in these answers.
public static void printDigits(int num) {
while(num>0) {
int remainder = num%10;
num = num/10;
System.out.println(remainder);
printDigits(num);
}
}
You can use recursion to make it even more efficient.
You need to write int y = x % 10; inside the loop to "pull apart" every digit and print the digit y you have "pulled out".
Remove the System.out.println around your function calls.
You don't need to return a number, so you can change your return type to void:
public class Main {
public static void main(String[] args) {
printDigits(1362);
System.out.println();
printDigits(985);
}
public static void printDigits(int x) {
while (x > 0) {
int y = x % 10;
System.out.println(y);
x = x / 10;
}
}
}

Calculating factorial, where did I go wrong?

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.

generating random numbers in java and finding percentage of how many are less than or equal to 50

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

Recursive method that prints the digits of the number line by line

I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)

Converting decimal to binary in Java

I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand.
What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages:
The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
Multiple markers at this line
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable Binary
Multiple markers at this line
Syntax error on token "mod", invalid AssignmentOperator
Syntax error on token "mod", invalid AssignmentOperator.
Integer.toBinaryString(int) should do the trick !
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.
Working code :
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.
There are a two main issues you need to address:
Don't declare a method inside another method.
Your loop will never end.
For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.
For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation:
int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.
For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.
mod is not a valid operator, the syntax you wanted was %
You can use System.out.print to print on the same line rather than println
Try these corrections and let me know how you get on:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
Here is a small bittesting code I made for Android.
int myres = bitTest(7, 128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards
Mikael Andersson
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}

Categories

Resources