TLE in Fast Multiplication in spoj - java

How can I make this code faster?
Spoj said time limit exceeded when I paste this solution.
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("the number of multiplications <= 1000: ");
int n = scanner.nextInt();
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply");
BigInteger l1 = new BigInteger(scanner.next());
System.out.print("Second number to multiply");
BigInteger l2 = new BigInteger(scanner.next());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
} else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
}
}
update: I have now used a buffered reader but now I'm getting wrong answer even though my outputs are right. Here's my updated code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("the number of multiplications <= 1000: ");
int n = Integer.parseInt(reader.readLine());
if (n <= 1000) {
for (int i = 1; i <= n; i++) {
System.out.print("First number to multiply: ");
BigInteger l1 = new BigInteger(reader.readLine());
System.out.print("Second number to multiply: ");
BigInteger l2 = new BigInteger(reader.readLine());
if (l1.toString().length() == 10000 || l2.toString().length() == 10000) {
System.err.println("numbers to multiply should be at most 10000 decimal digits each.");
} else {
System.out.println("Product: "+l1.multiply(l2));
}
}
} else {
System.err.println("number of multiplications should be less than or equal to 1000");
}
} catch (NumberFormatException e) {
System.err.println("invalid");
}
}
}
Thanks in advance.

Reading input in java is very slow if you use Scanner. You can pass only problems with really small input using it. You should use BufferedReader and BufferedWriter if you think the input can be larger. The rest of your algorithm is correct(although this problem is meant for testing own implementation of big integer numbers instead of built-in types).
EDIT: you are getting WA because of all the helper output you print to system.out. In programming competitions you should write nothing but the answer on the standard output. Thus you need to print only the result of the multiplication. Use the example. Your output should be precisely the same for your solution to pass.

Related

trying to learn how to error check my code

I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);

NoSuchElementException with Java.Util.Scanner with array

I m very new to java and don't know why I'm getting this error when I run below program
program : this program basically read no of input N in first line and then scan each number and store it in array arr and display it.
range of N is : 0<N<10^6
input numbers can be long so that I used long array in the program.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
long no = sc.nextLong();
if(no > 1000000 || no < 1)
System.exit(0);
long arr[] = new long [(int)no];
for(int i=0;i<(int)no;i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
}
}
input values : here you find input values
output :
Runtime Errors
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextLong(Scanner.java:2265)
at java.util.Scanner.nextLong(Scanner.java:2225)
at Solution.main(Solution.java:23)
rest of output is here
You are repeatedly calling nextLong(), but not testing to see if there is a next long:
for(int i=0;i<(int)no;i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
You need do something like this:
for(int i=0;i<(int)no && sc.hasNextLong();i++) {
arr[i] = sc.nextLong();
System.out.println(arr[(int)i]);
}
It's supposed to be something like this:
import java.util.Scanner;
import java.io.InputStream;
class Solution {
public static void main(String... args) {
InputStream in;
// initialize in
Scanner scanner = new Scanner(in);
int[] numbers;
// You don't need to store long values because int values fall within 0 and 10^6
try {
numbers = new int[(scanner.hasNextInt()? scanner.nextInt(): 0)];
} catch(NegativeArraySizeException nase) {
numbers = new int[0];
}
// we store the limits in variables so that your system doesn't create them repeatedly in each iteration
for(int i = 0, number, LOW = 0, HIGH = 1000000; scanner.hasNextInt() && i < numbers.length;) {
number = scanner.nextInt();
if(number > LOW && number < HIGH) {
numbers[i] = number;
// go to next index only if we have a number
i++;
}
}
}
}

Recursive Factorial Java

First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.
Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.
Here is code thus far:
import java.util.Scanner;
public class Recursive
{
public static void main(String[] args)
{
int number; // To hold a number
char letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
number = keyboard.nextInt();
//Display the factorial
System.out.println(number + "! is " + factorial(number));
}
private static int factorial(int n)
{
if (n == 0)
return 1; // Base Case
else if (n > 0)
return n * factorial(n-1);
else (!(n>0))
return
System.out.println(number + "is invalid");
}
}
After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial
while (true) {
// Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
int number = keyboard.nextInt();
if (Pattern.matches("\\d+", String.valueOf(number))) {
if (Integer.valueOf(number) == 0)
System.exit(0);
// Display the factorial
System.out.println(number + "! is " + factorial(number));
}
else
System.out.println("Error");
}
My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.
public static void main(String[] args)
{
Integer number; // To hold a number
String letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
while(keyboard.hasNext()){
letter = keyboard.next();
try{
number = Integer.parseInt(letter);
if(number==0){
//Exiting
break;
}
int fact = factorial(number);
//Display the factorial
System.out.println(number + "! is " + fact);
System.out.print("Enter an integer to find the factorial: ");
}
catch(NumberFormatException e){
System.out.println("Invalid input please enter integers only");
}
}
}
Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.
My solution for recursive factorial using Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
class Main {
public static String factorial(int n,String s){
if(n>0){
BigInteger fact = new BigInteger(s);
fact = fact.multiply(new BigInteger(n + ""));
return factorial(n-1,fact.toString());
}
else{
return s.toString();
}
}
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
if(n==0)
System.out.println("Factorial is 0");
else{
String s = factorial(n,"1");
System.out.println("Factorial is " + s);
}
}
}
the example of factorial using recursive in Java
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}

How to calculate exponent with loop?

I am currently working on a program that calculates the power of certain numbers. The number limit is 1 to 9. My code is posted below. I have the following issues:
Every time I run the program it doesn't print the correct answer.
I want to modify the code so the application calculates X to power of Y, where X and Y are allowed to be integers in the range 1 to 9 (including 9). If the user enters an invalid value the program should ask the user for input again. When a user is done with entering the values for base and exponents, the program will print the result.
Conditions of this task is that I must use loops to calculate the result by doing
several multiplications; I am not allowed to use any available method or API
that calculates the result for me. Please help me come up with the solution.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package exponent;
//import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
int t = 1;
for(int i = 1;i <= e; i++);
{
t=t*b;
}
System.out.println(t);
}
// TODO code application logic here
}
For a start, there should be no semi colon after the for loop:
for(int i=1;i<=e; i++ )
{
t=t*b;
}
A simple input test could be something along the lines of:
public boolean testInput(int e)
{
if(e>9||e<1)//where e is the inputted number
{
return false
}
else
{
return true;
}
}
Then use it like this:
boolean valid = false;
while(valid!=true)
{
e = Integer.parseInt(br.readLine());
if(testInput(e)==false)
{
System.out.println("Please enter a number between 1 and 9")
continue;
}
else
{
valid = true;
}
}
Remove semi colon from for-loop
From
for(int i=1;i<=e; i++ );
to
for(int i=1;i<=e; i++ )
For the first part, its is a easy fix. You just added a semicolon where there shouldn't be in the for loop.
for(int i = 1;i <= e; i++); {
for(int i = 1;i <= e; i++){ //There should be no semicolon here
For the second part, you can do it with two very easy do-while loops.
//Replace this
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
//with
do{
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1);
do{
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1);
So the do-while loops, will first ask for the base or the power (Depending where in the code the program is running), then it will set the int to the value. If the value is greater than 9, ie: 10 or above, the program will reask for the base or power (Like I said, depended which loo is running), and then it will set the int again. It will do this, until the value is under 10. Like you want.
Here is an example of the output:
Enter the base
56
Enter the base
-4
Enter the base
4
Enter the power
67
Enter the power
10
Enter the power
-8
Enter the power
7
4 to the 7th power is 16384
If the code snippets are confusing, here is the entire compilable, working class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StackOverflowAnswers{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
do{ //Asks for the base
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
}while(b > 9 || b < 1); //If the base is not valid, it goes back to the "do" statement, which asks for the base, again.
do{ //Asks for the power
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
}while(e > 9 || e < 1); //If the power is not valid, it goes back to the "do" statement, which asks for the power, again.
int t = 1;
for(int i = 1;i <= e; i++){ //No semicolon here
t=t*b;
}
System.out.println(b + " to the " + e + "th power is " + t); //Just added some words and the base and the power for easier debugging and understanding.
}
}
Hope this helps.
For the first part, it is just happening because you placed a semicolon after loop's declaration, which java just loops to that semicolon and nothing more. By removing semicolon the loop should work. However, for the second part, you can just add inputcheck method, as shown in my code below.
import java.io.*;
public class abc {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b, e;
System.out.println("Enter the base");
b = check(Integer.parseInt(br.readLine()));
System.out.println("Enter the power");
e = check(Integer.parseInt(br.readLine()));
int t = 1;
for (int i = 1; i <= e; i++); {
t = t * b;
}
System.out.println(t);
}
private static int check(int x) {
while (x < 1 || x > 10)
x = Integer.parseInt(br.readLine());
return x;
}

Illegal character error when compiling simple hasse algorithm program in java

I cant seem to figure out why the below code won't compile. I get up an error for the line saying: if ((number % 2) == 0) {. The error message says: "illegal character". The program is supposed to take a number n. If the n == to 1, the program stops. If n is odd it, then the new n == (n*3)+1. If n is even, new n == n/2.
import java.util.Scanner;
import java.lang.Math.*;
public class HasseAlgoritme {
public static void main(string [] args) {
Scanner tastatur = new Scanner(System.in);
System.out.print("Input the first starting number");
int number = tastatur.next();
while (number != 1) {
System.out.print(number);
if ((number % 2) == 0) { 
System.out.println(number);
}
else {
number = (number*3)+1;
System.out.print(number);
}
}
}}
public static void main(string[] args)
Should be
↓
public static void main(String[] args)
Java is case sensitive!
Also number should be String and not an int, this won't compile (or use nextInt instead of next).
Read integer using this : int number = tastatur.nextInt(); or this : int number = Integer.parseInt(tastatur.next());.
If a number is being entered the scanner should use nextInt()
int number = tastatur.nextInt();
tastatur.nextLine();
Also tastatur.next(); returns String, you might want to use tastatur.nextInt(); instead
Change Scanner.next() to Scanner.nextInt()
this will compile.I have closed the scanner. and You are running infinite while loop
import java.util.Scanner;
public class HasseAlgoritme {
public static void main(String [] args) {
Scanner tastatur = new Scanner(System.in);
System.out.print("Input the first starting number");
int number = Integer.valueOf(tastatur.next());
while (number != 1) {
System.out.print(number);
if ((number % 2) == 0) {
System.out.println(number);
}
else {
number = (number*3)+1;
System.out.print(number);
}
}
tastatur.close();
}
}

Categories