I am trying to find out 2 to the power n. I used recursive function for this.
My Code:
class TwoPowerN
{
static BigInteger twoPowern(BigInteger x, long y)
{
BigInteger temp = new BigInteger("1");
if( y == 0)
return new BigInteger("1");
temp.equals(twoPowern(x, y/2));
if (y%2 == 0)
return temp.multiply(temp);
else
return x.multiply(temp.multiply(temp));
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = Integer.parseInt(br.readLine());
while(t>0)
{
long r = Long.parseLong(br.readLine());
BigInteger a = new BigInteger("2");
BigInteger ans=twoPowern(a,r);
pw.println(ans);
t--;
}
pw.close();
}
}
But I don't get the required result.
For cases 1 2 3 4 5 I am getting 2 1 2 1 2. A similar program(using similar function but with int) in 'C' works fine.
Can anyone explain what is the mistake?
I think that you need to assign the recursive result, rather than test for equality:
temp.equals(twoPowern(x, y/2)); // This is checking for equality
Should be
temp = twoPowern(x, y/2); // This is assigning the value
temp.equals(twoPowern(x, y/2));
is a conditional statement in java, not an assignment, so you aren't
storing the recursive value.
This is a lot simpler:
public class power2 {
public static long power2( int power)
{
if(power <= 0)
return 1;
return 2 * power2(power-1);
}
static BigInteger twoPowern(long y)
{
if( y == 0) {
return BigInteger.ONE;
}
return new BigInteger("2").multiply(twoPowern(y-1));
}
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
System.out.println("2^" + i + "," + power2(i));
System.out.println("2^" + i + "," + twoPowern(i));
}
}
}
Using regular longs, or BigInteger.
Related
I am solving this problem from HackerEarth but I am getting the "Time limit exceeded" error.
Function F(N) is defined as:
F(N) = sum_of_digits(N2)
Given a number N, output if it is possible for it to ultimately become {1 or 4} or not.
Input:
First line contains T which is the number of test cases.
T lines follow each with an integer N.
Output:
For each N output "YES" or "NO" if the number can achieve desired goal or not.
This is the program:
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Stream;
public class MoodyNumbers {
public static boolean is1or4(int x) {
boolean result = false;
Integer digitSum = Stream.of((int) Math.pow(x, 2)).reduce(Integer::sum).get();
StringBuilder sumStringBuilder = new StringBuilder(String.valueOf(digitSum));
for (int i = 0; i < sumStringBuilder.length(); i++) {
result = sumStringBuilder.charAt(i) == '1' || sumStringBuilder.charAt(i) == '4';
if (result) {
break;
}
}
return result;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedOutputStream bos = new BufferedOutputStream(System.out);
int numberOfTest = Integer.parseInt(br.readLine());
for (int i = 0; i < numberOfTest; i++) {
boolean result = is1or4(Integer.parseInt(br.readLine()));
if (result) {
bos.write("YES\n".getBytes());
}
else {
bos.write("NO\n".getBytes());
}
bos.flush();
}
}
}
I ran out of ideas to make this faster, any recommendations?
What takes time is writing to standard output, so if you write the result to standard output for each test case, that will increase the overall time significantly.
You can use StringBuilder and append to it the result of each test case. Then after you have handled all the test cases, print out the entire contents of the StringBuilder.
Also, I think you misunderstood the question. Your code checks whether the sum of the digits of the square of the test case number (i.e. the result of function F(N)) contains a 1 (one) or a 4. As I understand it, you need to check whether the result of F(N) is 1 or 4.
Here is my solution which was accepted on hackerearth, i.e. it produced the correct results in an acceptable time.
import java.util.Scanner;
public class MoodyNumbers {
private static boolean is1or4(int x) {
boolean result = x == 1 || x == 4;
if (!result) {
int newX = sumDigits((long) x * x);
if (newX == 1 || newX == 4) {
return true;
}
if (newX == 9 || newX == 16) {
return false;
}
result = is1or4(newX);
}
return result;
}
private static int sumDigits(long x) {
int sum = 0;
while (x >= 10) {
sum += x % 10;
x /= 10;
}
sum += x;
return sum;
}
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int numberOfTestCases = stdin.nextInt();
StringBuilder sb = new StringBuilder(numberOfTestCases * 4);
String newLine = System.lineSeparator();
while (numberOfTestCases-- > 0) {
int n = stdin.nextInt();
sb.append((is1or4(n) ? "YES" : "NO"));
sb.append(newLine);
}
System.out.print(sb);
}
}
If the result of F(N) is either 9 or 16, that creates an endless loop. F(9) returns 9. F(16) returns 13 and F(13) returns 16 which also creates an endless loop. Hence for any number for which F(N) eventually returns either 9 or 16, the result is NO.
I would like to checking if an element is even or odd. What is wrong with my code?
bad operand types for binary operator '%' first type: java.lang.String second type: int, line 16
incompatible types: java.util.ArrayDeque cannot be converted to java.util.ArrayList, line 44
class ArrayExample{
public void printMethod(ArrayList<String> theList){
String value = null;
for (int n=0; n < theList.size(); n++){
value = theList.get(n);
//checking if an element is even or odd
if (value.length % 2 == 0){
System.out.println("even");
System.out.println(value);
} else {
System.out.println("odd");
System.out.println(value);
}}}}
class Calc {
public static void main(String[] args) {
ArrayDeque<String> storeQueue = new ArrayDeque<String>();
for (int i = 0; i < 40; i++) {
Random rand = new Random();
int value = rand.nextInt((40 - 1) + 1) + 1;
String z = new String(new char[value]).replace("\0", "z");
storeQueue.add(z);
System.out.println(storeQueue);
}
ArrayExample samp = new ArrayExample();
samp.printMethod(storeQueue);
}}
I think you can simply using ArrayList instead of ArrayDeque unless you want to perform FIFO operation. Also you might realised that your array is consisted of String, mod operation here should take input as integer. So you can use this random:
Random random = new Random();
int randomInteger = random.nextInt();
Here are the 2 changes required to make the program work:
Change the operands of % operator to Integer (Use value.length in place of value)
Change the argument to printMethod from ArrayDeque type to 'ArrayList' type.
Here is the working solution, with these 2 changes:
// File name: Calc.java
import java.util.*;
class ArrayExample{
public void printMethod(ArrayList<String> theList) {
String value = null;
for (int n=0; n < theList.size(); n++){
value = theList.get(n);
//checking if an element is even or odd
if ((value.length()) % 2 == 0) {
System.out.println("even - " + value);
} else {
System.out.println("odd - " + value);
}
}
}
}
public class Calc {
public static void main(String[] args) {
ArrayDeque<String> storeQueue = new ArrayDeque<String>();
for (int i = 0; i < 40; i++) {
Random rand = new Random();
int value = rand.nextInt((40 - 1) + 1) + 1;
String z = new String(new char[value]).replace("\0", "z");
storeQueue.add(z);
System.out.println(storeQueue);
}
ArrayExample samp = new ArrayExample();
samp.printMethod(new ArrayList<String>(storeQueue));
}
}
Output:
> javac Calc.java
> java Calc
[zzzzzzzzzzzzzzzzzzzz]
[zzzzzzzzzzzzzzzzzzzz, zzzzzz]
[zzzzzzzzzzzzzzzzzzzz, zzzzzz, zzzzzzzzzzzzzzzzzzz]
[zzzzzzzzzzzzzzzzzzzz, zzzzzz, zzzzzzzzzzzzzzzzzzz, zzzzzzzzzzzzzzzzzzzzzzzzzzzz]
...
...
...
even - zzzzzzzzzzzzzzzzzzzz
even - zzzzzz
odd - zzzzzzzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
odd - zzzzzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzz
odd - zzzzzzzzzzzzzzz
odd - zzzzzzzzz
odd - zzzzzzzzzzz
even - zzzzzzzzzzzzzz
even - zzzzzzzzzzzzzzzzzzzzzz
odd - zzzzz
even - zzzz
even - zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
In your class ArrayExample method printMethod expect ArrayList as parameter, but in main method you try to pass ArrayDeque which is not compatible with ArrayList.
To resolve this problem you should change parameter declaration in printMethod to ArrayDeque, but still there is a problem becouse ArrayDeque dont have .get method.
I propose to change body of method to foreach loop.
And another bug in this code is you try modulo on String but you need do it on its length. You cannot modulo on text, rather you should use it on text length.
class ArrayExample {
public void printMethod(ArrayDeque<String> theList) {
String value = null;
for (String s : theList) {
if (s.length() % 2 == 0) {
System.out.println("even");
System.out.println(value);
} else {
System.out.println("odd");
System.out.println(value);
}
}
}
}
And you main class can stay the same as you write.
It works - #Gopinath
// File name: Calc.java
import java.util.*;
class ArrayExample{
public void printMethod(ArrayList<String> theList) {
String value = null;
for (int n=0; n < theList.size(); n++){
value = theList.get(n);
//checking if an element is even or odd
if ((value.length()) % 2 == 0) {
System.out.println("even - " + value);
} else {
System.out.println("odd - " + value);
}
}
}
}
public class Calc {
public static void main(String[] args) {
ArrayDeque<String> storeQueue = new ArrayDeque<String>();
for (int i = 0; i < 40; i++) {
Random rand = new Random();
int value = rand.nextInt((40 - 1) + 1) + 1;
String z = new String(new char[value]).replace("\0", "z");
storeQueue.add(z);
System.out.println(storeQueue);
}
ArrayExample samp = new ArrayExample();
samp.printMethod(new ArrayList<String>(storeQueue));
}
}
This is an homework problem
Is there a way tor reverse a number in Java without using any loops? The only solution I can think of is reversing it using String and then casting it back to an integer.
If you want to reverse a number withour using any loop you can use Recursion method call. Following program is doing same
public static void reverseMethod(int number) {
if (number < 10) {
System.out.println(number);
return;
} else {
System.out.print(number % 10);
reverseMethod(number / 10);
}
}
public static void main(String args[]) {
int num = 4567;
reverseMethod(num);
}
Even if you were to reverse the number by casting it into a String, you would still need a loop if you want the program to work when having ints of different sizes. If I were to make a method to reverse a number but could not do it with loops, I would probably do it with recursion (which still uses loops indirectly). The code will look something like this:
class Main {
public static void main(String[] args) {
String input = "1234"; // or scanner to take in input can be implemented
System.out.println(Integer.parseInt(reverseInt(input)));
}
public static String reverseInt(String x) {
if (x.length() == 1) {
return x;
} else {
return x.substring(x.length() - 1) + reverseInt(x.substring(0, x.length() - 1));
}
}
}
Hope this helps!
By using reverse() of StringBuilder:
int number = 1234;
String str = String.valueOf(number);
StringBuilder builder = new StringBuilder(str);
builder.reverse();
number = Integer.parseInt(builder.toString());
System.out.println(number);
will print:
4321
if you want reverse method without loop and recursion then use this code
int a=12345;
int b,c,d,e,f;
b=a%10;
c=a%100/10;
d=a%1000/100;
e=a%10000/1000;
f=a%100000/10000;
System.out.println(b+","+c+","+d+","+e+","+f);
you can go like :
public int reverse(int x) {
String o = "";
if (x < 0) {
x *= -1;
String s = Integer.toString(x);
o += "-";
o += new StringBuilder(s).reverse().toString();
}
else {
String s = Integer.toString(x);
o += new StringBuilder(s).reverse().toString();
}
try {
int out = Integer.parseInt(o);
//System.out.println(s);
return out; }
catch (NumberFormatException e) {
return 0;
}
}
This is a solution using recursive method call
public class Tester{
public static int findReverse(int num, int temp){
if(num==0){
return temp;
}else if(num<10){
return temp*10 + num; //up to this is stopping condition
}else{
temp = temp*10 + num%10;
return findReverse(num/10, temp);
}
}
public static void main(String args[]){
int num = 120021;
int reverseNum = findReverse(num, 0);
System.out.println(reverseNum);
if(num == reverseNum)
System.out.println(num +" is a palindrome!");
else
System.out.println(num +" is not a palindrome!");
}
}
This will be fast.
static int reverseNum(int num) {
StringBuilder sb = new StringBuilder(String.valueOf(num));
sb.reverse();
return Integer.parseInt(sb.toString());
}
So consider the following program-segment! I've tried to use the basic recursion function to determine the factorial of a number, but now using the BigInteger class.
public static BigInteger fact(int a)
{
BigInteger factorial = BigInteger.ONE;
BigInteger factz = BigInteger.ONE;
if(a == 1)
{
return factorial;
}
else
{
return factz.multiply(fact(a-1));
}
}
So when I try implementing this in a program, it returns the output as 1. Is it because BigInteger objects are immutable? Or am I missing something here?
There's an error in the code, you should put
BigInteger factz = BigInteger.valueOf(a);
instead of BigInteger factz = BigInteger.ONE;
The pseudocode of calculate factorial recursively looks as:
function factorial(n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
Implementing it with BigInteger will be:
public static BigInteger factorial(BigInteger n) {
if (n.equals(BigInteger.ZERO))
return BigInteger.ONE;
else
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static void main(String[] args) {
System.out.println(factorial(new BigInteger("100")));
}
An output will be:
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Note: recursion takes too much memory if n is large. In this case it's better to use some iterative algorithm to calculate factorial.
I don't get the relevance of the local variables and you need to use BigInteger.valueOf(a).
Your method can be expressed in just one line:
public static BigInteger fact(int a) {
return a == 1 ? BigInteger.ONE : BigInteger.valueOf(a).multiply(fact(a - 1));
}
Find factorial with and without recursion of any number.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter no to find factorial :");
BigInteger inputNo1 = input.nextBigInteger();
System.out.println("With recursion " + inputNo1 + "! Factorial = " + (factorial(inputNo1.intValue())));
System.out.println("Without recursion " + inputNo1 + "! Factorial = " + (findFactorial(inputNo1)));
}
private static String findFactorial(BigInteger inputNo1) {
int counter;
BigInteger increment = new BigInteger("1");
BigInteger fact = new BigInteger("1");
for (counter = 1; counter <= inputNo1.longValueExact(); counter++) {
fact = fact.multiply(increment);
increment = increment.add(BigInteger.ONE);
}
return String.valueOf(fact);
}
public static BigInteger factorial(int number) {
if (number <= 1)
return BigInteger.ONE;
else
return factorial(number - 1).multiply(BigInteger.valueOf(number));
}
My solution for finding the factorial using recursion with the BigInteger Class
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);
}
}
}
Output screenshot for the above code:
Take a look at this:
public static BigInteger fact(BigInteger a)
{
if(a.intValue()==1||a.intValue()==0)
{
return BigInteger.ONE;
}
else
{
return a.multiply(fact(a.subtract(BigInteger.ONE)));
}
}
The modifications are:
- Include 0!=1
- Because the function fact returns BigInteger the its argument must be BigInteger too!
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}