Output of Factorial program - java

I am writing a program that should output the factorial of any number which is inputted by the user. The program correctly gives an output from 0 to 12 but if I enter 13, the output is 1932053504 but in my calculator, 13! = 6227020800.
Also in 32! and 33!, the output is negative (32! = -2147483648). Starting 34!, the output is zero(0).
How can I fix this? I want the program to provide the correct output of any number entered by the user.
import java.util.Scanner;
import java.io.*;
public class one {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int val = in.nextInt();
int factorial = 1;
for (int i = 1; i <= val; i++) {
factorial *= i;
}
System.out.println("The factorial of " + val + " is " + factorial);
}
}

It exceeds the max value an integer can take
Max integer value:2147483647
Max long value: 9223372036854775807
Max double value: 7976931348623157^308
Use long, double or BigInteger, which doesn't have upper boundaries
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int val = in.nextInt();
int factorial = 1;
int i = 1;
while (i <= val) {
factorial = factorial * i;
i++;
}
System.out.println("The factorial of " + val + " is " + factorial);
}
}
That's how you'd do it with a while loop instead

Related

What am I missing from my code to meet all the requirements of my program?

I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.
public class Table {
public static void main(String [] strAng) {
int sum = 0;
double average;
int min = 1;
int max = 10;
for(int number = min;
number <= max; ++number) {
sum += number;
}
System.out.print("Sum:" +sum);
System.out.print("Average:" +average);
You have not get an input from user and also you do nothing to make average.
Try this code, and if you have other requirements, update the question.
int sum = 0;
double average;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the integers with space between each two integer: ");
String inputNumberFilePath = userInputScanner.nextLine();
String[] numStrArray = inputNumberFilePath.split(" ");
for (String string : numStrArray) {
sum += Integer.parseInt(string);
}
average = (double) sum / (double) numStrArray.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
output sample:
Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.
import java.util.*;
public class Table {
This part is used to read ANY user input Strings included.
public static String getInput(){
String outPut = "";
System.out.println("Type something to parse: ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextLine()) {
outPut = sc.nextLine();
}
return outPut;
}
Here we build our "bar graph":
public static Map<Long,Integer> makeTable(String input){
Map<Long,Integer> table = new HashMap<>();
long in = Long.parseLong(input);
long lastDig = 0;
int count = 1;
while(in > 0){
lastDig = in % 10;
in /= 10;
if(!table.containsKey(lastDig)) {
table.put(lastDig, count);
} else {
table.replace(lastDig,count,count+1);
}
}
return table;
}
Here we calculate the sum:
public static int sum(Map<Long,Integer> table){
int sum = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
}
return sum;
}
Here we get our average:
public static int average(Map<Long,Integer> table){
int sum = 0;
int divisor = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
divisor += table.get(key);
}
return sum/divisor;
}
public static void main(String[] args){
int sum = 0;
double average = 0;
String input = "";
input = getInput();
System.out.println("Unsanitized In: " + input);
Here the integer digits are extracted!
input = input.replaceAll("[^\\d.]","");
Long.parseLong(input);
System.out.println("Sanitized In: " + input);
Map<Long,Integer> myMap = makeTable(input);
System.out.println(myMap);
System.out.println("Sum:" +sum(myMap));
System.out.print("Average:" + average(myMap));
}
}
Our example output for: asdf45313ha is:
Unsanitized In: asdf45313ha
Sanitized In: 45313
{1=1, 3=2, 4=1, 5=1}
Sum:16
Average:3

I am trying to write a program that allows me to input multiple integers, but it won't allow me to enter in my set of integers

My code won't allow me to enter in multiple integers to where it can then compute the sum, the count of integers, the minimum, and the sum of positive even integers. I am not sure if I need another method or if im calling for the wrong things.
import java.util.Scanner;
public class Assignment2 {
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0;
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
//when code reads 0, code terminates
int[] numbers = new int[4];
for(int i=0; i<4; i++){
numbers[i] =sc.nextInt();
}
while(!(n==0)){
sum += n;
n = input.nextInt();
}
class SumOfValues {
public int sum(int...vals){
int sum=0;
for (int val : vals) {
sum+= val;
}
return sum;
}
}
class CountingInts{
public void main(String[] args){
Scanner input=new Scanner(System.in);
int count=0;
System.out.print("Numbers: ");
while (input.hasNextInt()){
input.nextInt();
count++;
}
System.out.print(count);
input.close();
}
}
int sumPositive = 0;
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers );
}
}
It looks like you are an absolute beginner, so I'd recommend not dealing with functions and classes and all that, and just write everything linearly. I'm not sure why you have all those functions, classes and variables, but to help you, this is probably the simplest way to achieve what you are trying to do.
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args) {
int sum = 0, minNumber = 0, nCount = 0, countEvenIntegers = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int input = sc.nextInt();
if (input == 0) {
break;
}
sum += input;
nCount += 1;
}
System.out.println("The minimum integer is " + minNumber);
System.out.println("The count of integers is " + nCount);
System.out.println("The sum of positive integers is " + sum);
System.out.println("The count of even integers in the sequence is " + countEvenIntegers);
}
}
Note that I've not added the minimum interger and count of even intergers for you to complete.
Not quite sure what you are doing in your code since you are not doing any operations on the variables you are outputting, and thus should not expect the output to be any other than 0.
Also, your inner classes are really weird.
Here is an example (based on your code) that does what you want. Plenty of ways of achieving your goal, but I think this is simple enough:
import java.util.Scanner;
import java.util.*;
public class Assignment2{
private static final Scanner input = null;
private static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int sum=0, minNumber=0, nCount=0, countEvenIntegers=0, sumPositive = 0;
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
while(true) {
int i = sc.nextInt();
if(i == 0) {
break;
}
numbers.add(i);
}
if(numbers.size() > 0) {
minNumber = numbers.get(0);
}
for (int number : numbers) {
sum += number;
if(minNumber > number) {
minNumber = number;
}
if(number % 2 == 0) {
countEvenIntegers++;
}
if(number > 0 ) {
sumPositive += number;
}
}
nCount = numbers.size();
System.out.println("The minimum integer is " + minNumber + "\nThe count of integers is "
+ nCount + "\nThe sum of positive integers is " + sumPositive + "\nThe count of even integers in the sequence is " +
countEvenIntegers + "\nThe total sum is " + sum);
}
}

Having trouble converting a character value to an integer value

import java.util.Scanner;
public class baseConverter {
//Main method
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String input = "";
System.out.println("What number base would you like to convert?");
int base = keyboard.nextInt();
//Checking if the base is between 2 and 9, inclusive
if (base >= 2 && base <=9){
System.out.println("Please enter a base " + base + " number:");
}else{
System.out.println("Please enter a base from 2 to 9");
}
input = keyboard.next();
int converted = compute(input, base);
System.out.println("The base-10 conversion of that number is " + converted);
}
//Where all the conversion will take place
public static int compute(String userString, int userBase){
int n = userString.length(), output = 0;
int[] num = new int[n];
//The for loop that does all the computing
for (int i = 1; i <= n; i++){
//assigning values to the array indeces
num[i-1] = Integer.parseInt(String.valueOf(userString.charAt(i-1)));
if(num[i-1] != 0){
output = output + ((userBase ^ (n-i)) * (num[i-1]-1));
}else{
output = output;
}
}
System.out.println("User base is " + userBase+ ". n is "+ n);
return output;
}
}
When I run this and input the base and 3 and the input as 2, it seems to convert the value '2' to it's ASCII value of 50 when storing it in the num array. I guess my question is if there is any way that I could work around this or what an entirely different way of getting the value from the string stored as an integer.

Separating an integer and adding the values with support for a negative integer

I have an assignment to break an integer into it's individual digits, report them back to the user, and add them. I can do that, but I'm struggling with supporting negative integers. Here's my code, which works exactly the way I want it to, but only for positive integers:
import java.util.*;
public class Module4e
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i]);
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I've found plenty of hints for getting this to work with positive integers, but none for negatives.
Use RegExp
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestDigits {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Validate Input
String number = console.nextLine();
Pattern p = Pattern.compile("(-?[0-9]{1})+");
Matcher m = p.matcher(number);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid Numbers");
}
// Calculate
p = Pattern.compile("-?[0-9]{1}+");
m = p.matcher(number);
int result = 0;
System.out.print("The digits of the number are: ");
while (m.find()) {
System.out.print(m.group() + " ");
result += Integer.valueOf(m.group());
}
System.out.println("");
System.out.println("Result " + result);
}
}
// I think you can use this code //also you can multiply the number by -1
int positive = 0;
//positive give you information about the number introduced by the user
if (myNum.charAt(0)=='-'){
positive=1;
}else{
positive=0;
for (int i=positive; i<myNum.length(); i++){
//be carefull with index out of bound exception
if ((i+1)<myNum.length()){
upNum[i]=myNum.substring(i,i+1);
}
}
Change the statement String myNum=console.nextLine() to String myNum = String.valueOf(Math.abs(Integer.valueOf(console.nextLine())));
You do not have to use String to solve this problem. Here's my thought.
import java.util.*;
public class Module4e throws IllegalArgumentException {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
if (!console.hasNextInt()) throw new IllegalArgumentException();
int myNum=console.nextInt();
myNum = Math.abs(myNum);
int sum=0;
System.out.println("\n");
System.out.print("The digits of the number are: ");
While (myNum > 10) {
System.out.print(myNum % 10);
System.out.print(" ");
sum += myNum % 10;
myNum /= 10;
}
System.out.println(myNum);
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Try this. I gave -51 as input and got -6 as output. This is what you are looking for?
import java.util.*;
public class LoggingApp
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
int multiple = 1;
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
Integer myNumInt = Integer.parseInt(myNum);
if (myNumInt < 1){
multiple = -1;
myNum = Integer.toString(myNumInt*-1);
}
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i])*multiple;
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}

How to add a long integer to existing program

The code works. But, I need to include long integers. How can I do that? I've tried a million things. I'm not good at this either so it takes me 5 times longer to get a simple code. Please help.
import java.util.Scanner;
public class Exercise2_6M
{
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();
// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}
// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}
public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}
Read the input value as a string and then use the BigInteger class to perform calculations with very large values​​.
A recursive solution can be much leaner:
import java.util.Scanner;
public class Exercise2_6M
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
System.out.print ("Enter an long:");
long lng = input.nextLong ();
int sum = getDigitSum (lng);
System.out.println ("Sum all digits in " + lng + " is " + sum);
}
public static int getDigitSum (long num)
{
if (num < 10L) return (int) num;
else return ((int)(num % 10)) + getDigitSum (num/10L);
}
}

Categories