how to show the negative number factorial in this code - java

im trying to make a calculator and im was unable to continue because of some confusion in my codes. i was trying to make a factorial of a number, if its a positive number there is no error but every time i input a negative number it results to 1, here is my code .
import java.math.BigInteger;
import java.util.Scanner;
public class Factorial2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = s.nextInt();
String fact = factorial(n);
System.out.println("Factorial is " + fact);
}
public static String factorial(int n) {
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
}
i already tried making if statements but still it results to 1.i also want to make the negative factorial into a display text not the value of the negative factorial

You need to validate the input before the calculation, example:
public static String factorial(int n) {
if(n < 1) return "0";
BigInteger fact = new BigInteger("1");
for (int i = 1; i <= n; i++) {
fact = fact.multiply(new BigInteger(i + ""));
}
return fact.toString();
}
Of course you can define any default return value or throw an error:
if(n < 1) throw new RuntimeException("Input must be > 0");

Related

What is wrong with this program. if a number is perfect for example num is 6 it should print 1*2*3. used BigInteger

package perfect;
import java.math.BigInteger;
import java.util.Scanner;
public class Perfect {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
BigInteger n = input.nextBigInteger();
BigInteger sum = BigInteger.valueOf(0);
BigInteger i = BigInteger.valueOf(1);
BigInteger mul = BigInteger.valueOf(1);
for(; i.compareTo(n)< 0; i.add(BigInteger.ONE))
{
if(n.mod(i).equals(BigInteger.ZERO))
{
sum = sum.add(i);
mul = mul.multiply(i) ;
}
}
if(sum == n)
{
System.out.println(n+ "=" +mul) ;
}
else
{
System.out.println("the given number " +n+ " is not a perfect
number");
}
}
}
as it has to print 6 = 1*2*3 i used BigInteger. but it is not showing any error but the program after taking a number from user in the console i am not getting any output.
Three problems:
BigInteger is immutable, so you should do i = i.add(BigInteger.ONE) instead
When comparing sum with n, you should do sum.equals(n) instead
Store factors into a list instead of cumulatively multiplying them back to the input
Code will look nicer if you format it
import java.math.BigInteger;
import java.util.Scanner;
import java.util.ArrayList;
public class Perfect {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
BigInteger n = input.nextBigInteger();
BigInteger sum = BigInteger.valueOf(0);
BigInteger i = BigInteger.valueOf(1);
ArrayList<BigInteger> factors = new ArrayList<BigInteger>();
for (; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
if (n.mod(i).equals(BigInteger.ZERO)) {
sum = sum.add(i);
factors.add(i);
}
}
if (sum.equals(n)) {
System.out.print(n + "=" + factors.get(0));
for (int idx = 1; idx < factors.size(); idx++) {
System.out.print("*" + factors.get(idx));
}
System.out.println();
} else {
System.out.println("the given number " + n + " is not a perfect number");
}
}
}

Factorial of a number display issues

I know how to code to find the factorial of a number:
public static void factorialcalculations()
{
int usernumber, calculation, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
usernumber = in.nextInt();
if ( usernumber < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( calculation = 1 ; calculation <= usernumber ; calculation++ )
fact = fact*calculation;
System.out.println("Factorial of "+usernumber+" is = "+fact);
{
But what I need is for is to display what numbers it is being multiplied by for example if it was 5
I need it to display the factorial is: 5*4*3*2*1=120
Use recursion. The value you want to display for n=1 is "1=". For any other n, it's "n*" + display(n-1).
display(2) => "2*" + display(1) => "2*1="
display(3) => "3*" + display(2) => "3*2*1="
and so on.
There is lot of ways to do it. With your existing code you can print it within your existing loop. Recursive will be the elegant way to find the factorial.
public static int factorial(int n) {
System.out.print("factorial is : ");
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
System.out.print(i!=1 ? (i+"*"): (i+"="));
}
System.out.println(result);
return result;
}
PS: As a best practice you need to handle the all scenarios in here. (String/negative/.. inputs)
Here is what you seem to be looking for man:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println(getFactString(n,result));
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static String getFactString(int n, int result){
String output= "";
int count = n;
for (int i = count; i > 0; i--) {
if (n==1) {
output = output + n +" = ";
break;
}
output = output + n+" * ";
n--;
}
return output + result;
}
It's also possible to do this will StringBuilder as well. With the getFactorString() method, it doesn't matter what n is, you will get the correct string returned to display.

Finding unique numbers

I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}

Reversing a user input digit using methods

I want to take any user input integer between 1 and 9999 and return that number with its digits reversed. The problem with my code is it's returning the sum of the entered integer and I have no idea how to fix it. This is the code that that I came up with so far:
import java.util.Scanner;
class Reverse{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 1 and 9999: ");
int user = input.nextInt();
if(user>1 && user<9999){
System.out.println("The number with its digits reversed is : " + reverseDigit(user));
}else{
System.out.println("Invalid Input");
}
}
public static int reverseDigit(int num){
return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000); //This is the problem
}
}
You could replace :
return (num%10 + (num%100)/10 + (num%1000)/100 + num/1000);
with:
return ((num%10)*1000 + ((num%100)/10 )*100+ ((num%1000)/100)*10 + num/1000);
The reason that the first was wrong is because you get:
last digit:num%10
third digit:num%100)/10
second digit:(num%1000)/100
first digit:num/1000
so you was just adding all the digits before
But the Above works only for numbers from 1000-9999 .So you could replace the reverseDigit method with this simple method that works for every number:
public static int reverseDigit(int num){
int reverse=0;
while( num != 0 )
{
reverse = reverse * 10;
reverse = reverse + num%10;
num = num/10;
}
return reverse;
}
First, convert the number into a string then reverse the string and reconvert it into a number.
public static int reverseDigit(int num)
{
String str;
str = String.valueOf(num);
str = new StringBuilder(str).reverse().toString();
return (Integer.parseInt(str));
}
public static int reverseDigit(int num) {
int result = 0;
while(num != 0 ) {
result *=10;
int temp = num % 10;
result += temp;
num /=10;
}
return result ;
}
To do it using int (although String would be better).
public void test() {
System.out.println("Reversed: " + 1234 + " = " + reverseDigits(1234, 4));
}
public static int reverseDigits(int num, int digits) {
int reversed = 0;
for (int i = 0; i < digits; i++) {
reversed *= 10;
reversed += num % 10;
num /= 10;
}
return reversed;
}

Java Factorial using GUI only returns the first output

I have a program which should generate the factorial of any given number n.
When the user enters a number, the output is the factorial for every number entered after that into the calculator.
The code compiles fine but the calculator will not calculate any factorial except for the first.
As i can't use recursion for solving this problem please post only answers without using recursion.
Here's the code:
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
}
while(number1 != 1);
}
}
This code
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
needs to be repeated for each input.
I suggest that your GF put this into a method that can be called and the method will return the result.
import javax.swing.JOptionPane;
public class Assignment7
{
public static void main(String[] args)
{
int number1;
int factorial = 1;
String message;
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
do
{
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
number1 = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : "));
factorial = 1;
for(int i = 1; i <= number1; i++)
{
factorial = factorial * i;
}
}
while(number1 != 1);
}
}
You have to reset the number and the factorial to get the right factorial.
Also i would consider to use a head-controlled loop. Because it's easier to understand what is going on. Also maybe don't put the Inputdialog and the Parsing of the string to int into one line, it makes it a lot easier to handle wrong user-inputs, what you also should be doing.
Here my solution:
import javax.swing.JOptionPane;
class Assignment7 {
public static void main(String[] args) {
int number1 = 0;
int factorial = 1;
String message;
while (number1 != 1) {
String positiveInteger = JOptionPane.showInputDialog("Enter a positive integer that you would like factored (Type \"1\" to stop) : ");
// You could check if there was a user-input and also later check if it's a number.
if (positiveInteger.length() > 0) {
number1 = Integer.parseInt(positiveInteger);
}
for (int i = 1; i <= number1; i++) {
factorial = factorial * i;
}
message = String.format("The factorial of %d is: %d", number1, factorial);
JOptionPane.showMessageDialog(null, message);
//Reset everything
number1 = 0;
factorial = 1;
message = "";
}
}
}

Categories

Resources