I need to write a program that a user inputs a long positive number m. I need to find out what is the smallest int number n such that n! > m.
So far I have written such a code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
int fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println(count);
}
}
Test input:
6188989133
Correct output:
13
Your code output:
My code output is empty. What I am missing here?
You have to use long for the fact variable. When you use int the possible values are between -2,147,483,648 and 2,147,483,647.
However, you will never exceed the input number 6,188,989,133, so your while(fact <= number) loop will never exits. Every integer value possible will be smaller than 6,188,989,133. This explains why your code output is "empty", as it doesn't reach that System.out.println(count); line at all.
Keep in mind that the long type has such a limit as well, values can only be between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. When the input number is that big, you will not find the correct fact value which will be greater than the input because you are limited by the long type value range. As an example, for the input number 9,000,000,000,000,000,000 (which is inside the long type value range) the next factorial number is 51,090,942,171,709,440,000 (the value of 21!), which is outside the long type value range.
You can use the java.math.BigInteger class which has an "unlimited" range of possible values and do your math operations on BigInteger objects.
fact should be declared as long. Check the code below:
public class TestJava {
public static void main(String[] args) {
try{
System.out.println("Input number: ");
Scanner scanner = new Scanner (System.in);
long number = scanner.nextLong();
if(number >= 2432902008176640000L) {
// log an appropriate message like can not handle
// long value greater than 2432902008176640000L
return 21;
}
long fact = 1;
int count =1;
while (fact <= number) {
count ++;
fact *=count;
}
System.out.println("output: "+ count);
}catch(Exception e){
e.printStackTrace();
}
}
}
Update (Warning):
As #Pshemo mentioned, with out the if condition, the above code is fine till 20!, but after that it will cause the infinite loop problem. Hence this condition has to be taken care of. Code has been updated accordingly.
You need to change fact type to long
Related
public class Karatsubamultiplication {
public static void multiply(long ac , long ad, long bc, long bd, long digits)
{
double mul=0;
mul = Math.pow(10, digits) *ac + Math.pow(10, digits/2)*(ad+bc)+bd;
System.out.println("The multiplication answer is "+mul);
}
public static long[] splitnum(long n1) {
long[] split= new long[3];
long divider=1;
long num =0;
long counter=0;
num=n1;
while(num>0) {
num=num/10;
counter=counter+1;
}
split[2]=counter;
for(long i=0;i<counter/2;i++) {
divider*=10;
}
split[0]=n1/divider;
split[1]=n1%divider;
return split;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n1 and n2 ");
long n1 = sc.nextLong();
long n2 = sc.nextLong();
long ac=0,ad=0,bc=0,bd=0,digits=0;
if(n1/10==0 && n2/10==0)
{
System.out.println("The multiplication answer is "+n1*n2);
}
else
{
long[] a= splitnum(n1);
long[] c =splitnum(n2);
ac = a[0]*c[0];
ad = a[0]*c[1];
bc= a[1]*c[0];
bd= a[1]*c[1];
digits=a[2];
multiply(ac,ad,bc,bd,digits);
}
}
}
Multiplication of two 64 digit number_Gettin Input Mismatch Exception
Query : when i give 2 64 bit number result will be in 128 bits. Getting Input Mismatch exception:(
Need help to enhance this code in order to handle this exception .>
InputMismatchException is thrown by the nextLong() method, when the input entered by the user is not, in fact, a long.
The way you've used scanner means that nextLong is looking for a space, enter (newline), end of the stream, or other whitespace, and will then parse all the character that precede it as a long. Note that this means the input must consist of an optional + or -, and then a bunch of digits, and that is all, and that the number must fit between -2^63 and +2^63-1 (so, between -9223372036854775808 and +9223372036854775807). Any number below/above that isn't a long and therefore causes that exception.
Fix: Well, you tell me. What do you want this program to do? Any numbers outside of that range do not fit into the long datatype in the first place.
If you don't need your program to deal with numbers that extreme, then.. don't enter them.
If you do, then this code needs to be replaced entirely; don't call .nextLong() at all. Presumably, just call .next() and use java.math.BigInteger instead of longs, which can take numbers of any size.
The help I need is in JAVA coding, please. I'm having an extremely hard time learning this through online class instead of in person due to the pandemic going on. Any help is appreciated and thank you for taking the time to help a struggling student/parent!
Create a Scanner object that will be used for user input.
Prompt the user to enter an integer and store the value in a variable named num.
Call a method named getCount (details are given below) that will return the number of individual digits in the number that is between 3 and 6 (inclusive)
Display the original number and the number of digits between 3 and 6.
Create the method getCount that has a parameter of type int and returns a value of type int. This method will do the following:
Declare an integer variable named count and initialize it to 0.
Within a while or do-while loop, do the following:
Get the last digit of the parameter by getting the remainder after dividing by 10. Use the % operator to do this.
Call the inRange method, passing this digit as a parameter. If the inRange method returns true, add 1 to
count.
Use integer division by 10 on the parameter to change its value by getting rid of the last digit. Use the / operator to do this.
Stay in the loop as long as the parameter is greater than 0.
Create the method inRange that has a parameter of type int and returns a value of type Boolean. This method will return true if the parameter is between 3 and 6 (inclusive).
import java.util.*;
public class five {
public static void main(String[] args) {
int num;
Scanner kb = new Scanner(System.in);
System.out.print("Enter an integer: ");
System.out.print("Your number is ");
} // end main
public static boolean getCount(int) {
return int >= 3 && <= 6;
} // end getCount method
public static boolean inRange(int) {
return boolean
} // end inRange method
}
The output I'm attempting to get is
Enter an integer: 435678123
Your number is 435678123
It has 5 digits between 3 and 6.
Something like this would do the trick:
import java.util.Scanner;
public class five{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int x = 0;
System.out.print("Enter an integer: ");
x = sc.nextInt();
System.out.println("Your number is " + x);
System.out.println("It has " + getCount(x) + " digits between 3 and 6");
}
public static int getCount(int x){
int count = 0;
while(x > 0){
count += inRange(x%10) ? 1 : 0;
x/=10;
}
return count;
}
public static boolean inRange(int x){
return x >= 3 && x <= 6;
}
}
Output:
I am writing a program where the user must input 10 numbers and the output should be the highest number on the 10 inputs. But I don't know what's the next code that I will write.
import java.util.Scanner;
public class kzz {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int a = 1;
int value ;
while (a < 11) {
System.out.print("Enter Value No." + a + ":");
value = reader.nextInt();
a++;
}
}
}
What should I do now?
You are reading the first value into value, fine. Say it was 86. Next time through the loop you are reading the second value into the same variable, thereby overwriting the first. So the 86 are gone forever.
Instead I suggest a second variable highestValueSoFar. Store into it the value read only if it is higher. Then at the end this will contain the highest of the 10 values.
The program reads values from scanner until the value 0 is given, which finishes the process. The program will compile the sum only if all the numbers given are integers. In all the other situations (where not all of the values are integers) the program won't give anything out.
So i noticed my program gives out the sum of the integers even if there are other non integer values given and sometimes when they are all integers given it doesn't show the real sum just one of the numbers or something.
import java.util.Scanner;
public class Testing3{
public static void main(String[] args) {
int sum1 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number");
String number = input.nextLine();
int value =Integer.parseInt(number);
while(true) {
if (value!=0) {
number = input.nextLine();
if (Math.round(value)==value)//condition to integer{
sum1 = sum1 + value;
} else {
System.out.println(sum1);
break;
}
}
}
}
First of all, use while(true) or for(;;) to make in infinite loop
Second use nextInt() to read integers instead of doubles because you have no use for doubles. Alternatively, read strings with readLine and check their validity with Integer.parseInt.
Thirdly, you have a syntax error (so it shouldn't compile). You have an unmatched close brace near the else.
Lastly, remove the if (number != 0) because that will cause your program to continuously repeat in the loop without doing anything forever. Change the inside of the loop to:
number = input.nextInt();
if (number != 0){
sum1 = sum1 + number; //or use sum1 += number
} else {
System.out.println(sum1);
break;
}
I think your problem is at the place where you test for an integer. I don't think x mod 1 == 0 is correct suitable here. What I'll do when I am asked to check whether a number is an integer, I round the number and check if it equals to the original number.
Let's say we have a double variable called x and this evaluates to true if x is an integer:
Math.round(x) == x
I don't know whether there is a better way to do it but that's how I would do it and I like it.
I'm going to post the question and then the code that I currently have done. I feel like I'm pretty close to getting it but I'm stuck at one part I just can't seem to figure out. Here goes:
The question: Create a Vector that stores N numbers. Input N non-negative numbers through the console into the Array. Then create another Vector that stores only M prime numbers from the N numbers.
My code so far:
import java.util.*;
public class VectorPrimes {
public static Vector<Integer> inputVc = new Vector<Integer>();
public static Vector<Integer> primeVc = new Vector<Integer>(inputVc);
public static boolean isPrime(int n) {
boolean prime = true;
for (int i = 2; i * i <= n; i+= 2) {
if (n % i == 0) {
prime = false;
break;
}
}
return prime;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out
.println("This program will take input of positive numbers and output"
+ " prime numbers, if any, from the input numbers.");
System.out
.println("Input a positive number to check for prime numbers: ");
boolean looping = true;
while (looping) {
System.out
.println("Input '0' to finish inputting numbers and print the primes.");
String userin = scan.nextLine();
int input = Integer.parseInt(userin);
if (input != 0) {
System.out.println("Enter next number: ");
inputVc.add(input);
} else if (input == 0) {
//Integer[] inputArray = inputVc.toArray(new Integer[inputVc.size()]);
looping = false;
System.out.println(inputVc);
System.out.print(primeVc);
System.exit(0);
}
}
}
}
I'm sure it's not the best way to do it, but that's what I have so far. To be clear, I'm having trouble getting the inputted numbers from the input vector (inputVc) to go into the array (inputArray) and then storing the prime numbers in the prime vector (primeVc) and printing them. I have tried 3 or 4 different ways but I can't get anything to store in the primeVc vector, it just keeps printing blank.
I'm not asking for the code, what I'm trying to figure out is strictly how to get the prime numbers inputted into the primeVc vector and then print it. Of course the inputVc numbers need to be run through the isPrime method and then added to the primeVc vector if true, but I'm pretty sure that's where I'm having my problem.
What do you guys see?? I'm definitely missing something and cannot for the life of me figure it out.
Do something like:
//...
if (input != 0) {
System.out.println("Enter next number: ");
inputVc.add(input);
if (isPrime(input))
primeVc.add(input);
}
//...
Also you can create while(true) loop and simply break it when you will get 0.
first you have to call your functon isPrimethen if returned value is true then add it to your second list
and other thing, your function isPrime won't work, your initial value of 'i' is 2, then you are incrementing it by 2, so it will return value true for each odd number