I was trying to solve the simple problem posted on HackerRank.
https://www.hackerrank.com/contests/w16/challenges/sum-of-absolutes
I solved the problem, however its getting time out error to those with input array of size 100000. Could someone help me optimize this code below so it does not timeout.
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print outputto STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int n= in.nextInt();
int q = in.nextInt();
in.nextLine();
int[] a = new int[n+1];
for(int i=1;i<=n;i++)
{
a[i]= in.nextInt();
}
for(int j=0;j<q;j++)
{
int l = in.nextInt();
int r = in.nextInt();
int sum=0;
for(int k=l;k<=r ;k++)
{
sum = Math.abs(sum+a[k]);
}
if(sum%2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
}
}
I think you need to completely rethink your solution: You don;t actually need to work out the summation in order to establish if the result is odd or even.
The observation that adding two even numbers or two odd number gives you an even; and that adding an even and an odd give you an odd for all numbers (positive and negative) should be all you need.
Think about whether there's a shortcut that will give you the same odd/even answer. For example, -8 and 8 are both even while -3 and 3 are both odd. Do you really need to take an absolute value to determine if the sum is even or odd?
---Edit: Another thought or two---
First thought.
Please take a look at Bitwise and Bit Shift Operations. There are bitwise ways to figure out if the number is negative (namely: The high-order bit is 1). And there are bitwise ways to tell if the number is odd (namely: The low-order bit of a positive number is 1 and the low order bit of a negative number is 0).
--- Edit: Second thought---
Could you compress the array by not storing the input numbers, but instead the parity of those numbers? For example, you could use boolean[] isOdd or BitSet isOdd? You could store -7 in position i as isOdd[i] = true; or isOdd.set(i);. (Since BitSet and boolean both initialize to all false, you would not change the boolean or BitSet in position j if position j were even; see BitSet.) Then your answer would consist of counting the odds (or flipping a boolean or not'ing a bit) in the requested set and answering odd if the sum were odd (or false or 0) or even if the sum were even (or true or 1).
Why should you use a BitSet or boolean array? You can pack more information into less memory, making it easier for Java to find the space and leading to fewer page faults should you go over a page boundary.
I'm going to give you two hints. First, always look for needlessly repeated operations (spoiler: how many times do you do Math.abs on each value in the set?). And second, file IO is very expensive. Look for a way to use Scanner more efficiently.
Related
Here, I am finding number of perfect square numbers in given range.
But I am dealing with 'for' loop execution that takes much time for execution.
The index/key traverses from two numbers, lets say A to B, and does some operation in for loop.
The problem arises when there's large difference between A and B (e.g. A = 2 & B = 100000)
Can u suggest how can I reduce or optimize the execution time?
Scanner in = new Scanner(System.in);
int A = in.nextInt();
int B = in.nextInt();
int cnt = 0;
for(int number =A ; number<= B; number++){
int sqrt = (int) Math.sqrt(number);
if(sqrt*sqrt == number) {
cnt++;
}
}
System.out.println(cnt);
Or is it because of Math class operations that takes too much time to execute?
Can you suggest any alternate approach to find the square numbers between given range?
Thanks in advance!
I found an alternate way to find the count of perfect square numbers between given range.
This can be simply achieve by using Math.floor and Math.ceil operations.
Math.floor(Math.sqrt(B)) - Math.ceil(Math.sqrt(A)) + 1
Thanks! :)
Instead of going through each number in the range and figuring out if its a perfect square, I would suggest the below
Find a square root of the start number and find the integer part of it.
Lets say start number is 5. So integer part of the square root will be 2.
Now do the same for the range end number
Lets say end range was 1000, so the integer part of its square root would be 31. Now iterate from 2+1 to 31 and keep printing its square. That would give you the perfect squares between the given range.
Instead of the if(sqrt * sqrt == number) you could also check whether the double returned by Math.srt(number) is a integer. The algorithm would than become as follows:
for(int number =A ; number<= B; number++){
if((Math.sqrt(number) % 1) == 0) {
cnt++;
}
}
Note: Haven't tried the code myself so might not work as I expect.
Regarding the question on how you can improve the performance. The checking on whether the number is perfect could be done in parallel by executing per number a task. The access to the counter has to be synchronized than, (to be on the safe side).
This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
int numEven = 0;
int numOdd = 0;
boolean isEven;
do
{
System.out.print("Enter a number > 0: ");
n = scan.nextInt();
while (n > 0)
{
if (n % 2 == 0)
{
//n is even
isEven = true;
numEven++;
}
else
{
//n is odd
isEven = false;
numOdd++;
}
n /= 10;
}
//if numEven is even and numOdd is odd
if (numEven % 2 == 0 && numOdd % 2 == 1)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n >= 0);
}
}
There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...
int n;
do
{
int numEven = 0;
int numOdd = 0;
System.out.print("Enter a number: ");
n = scan.nextInt();
...
By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n > 0);
...
Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10
This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);
When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0
When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);
This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.
You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
boolean isEven;
do
{
System.out.print("Enter a number: ");
n = scan.nextInt();
//if 0, you leave the loop
if(n==0) {
System.out.println("You pressed 0, have a nice day");
break;
}
if (n % 2 == 0)
{
//it is even
isEven = true;
}
else
{
//it is not even
isEven = false;
}
//if even then he likes it, otherwise he does not
if (isEven)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
}
//put any contition here, lets say if you press 0 , you leave the loop
while (n != 0);
}
All the solutions online I can find use BigInteger but I have to solve this using arrays.
I'm only a beginner and I even took this to my Computer Science club and even couldn't figure it out.
Every time I enter a number greater than 31, the output is always zero.
Also, when I enter a number greater than 12, the output is always incorrect.
E.g. fact(13) returns 1932053504 when it should return 6227020800
Here's what I have so far:
import java.util.Scanner;
class Fact
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the number you wish to factorial");
int x = kb.nextInt();
System.out.println(fact(x));
}
public static int fact(int x)
{
int[] a = new int[x];
int product = 1;
for(int i = 0; i < a.length; i++)
{
a[i] = x;
x--;
}
for(int i = 0; i < a.length; i++)
{
product = product * a[i];
}
return product;
}
}
Maximum Values Make Large Numbers Terrible
Sadly, because of the maximum values of integers and longs, you are unable to go any larger than
For Longs:
2^63 - 1
9223372036854775807
9 quintillion 223 quadrillion 372 trillion 36 billion 854 million 775 thousand 807
and For Ints:
2^31 - 1
2147483647
2 billion 147 million 483 thousand 647
(I put the written names in to show the size)
At any point in time during the calculation you go over these, "maximum values," you will overflow the variable causing it to behave differently than you would expect, sometimes causing weird zeros to form.
Even BigIntegers have problems with this although it can go up to numbers way higher than just longs and ints which is why they is used with methods that generate massive numbers like factorials.
You seem to want to avoid using BigInteger and only use primatives so long will be the largest data type that you can use.
Even if you convert everything over to long (except the array iterators of course), you will only be able to calculate the factorial up to 20 accurately. Anything over that would overflow the variable. This is because 21! goes over the "maximum value" for longs.
In short, you would need to either use BigInteger or create your own class to calculate the factorials for numbers greater than 20.
The challenge is listed here:
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
I have written a code that works with the given 4 digit example, but doesn't work for 13 digits. I suspect there is some type of data overflow, but I am unsure. My super inefficient code is below.
public class Euler8 {
public static void main(String[]args){
String num = "/*number listed above*/";
int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13;
long sum=0, newSum;
for(int n=0; n<=987; n++){
n1=Character.getNumericValue(num.charAt(n));
n2=Character.getNumericValue(num.charAt(n+1));
n3=Character.getNumericValue(num.charAt(n+2));
n4=Character.getNumericValue(num.charAt(n+3));
n5=Character.getNumericValue(num.charAt(n+4));
n6=Character.getNumericValue(num.charAt(n+5));
n7=Character.getNumericValue(num.charAt(n+6));
n8=Character.getNumericValue(num.charAt(n+7));
n9=Character.getNumericValue(num.charAt(n+8));
n10=Character.getNumericValue(num.charAt(n+9));
n11=Character.getNumericValue(num.charAt(n+10));
n12=Character.getNumericValue(num.charAt(n+11));
n13=Character.getNumericValue(num.charAt(n+12));
newSum= (long)(n1*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13);
if(newSum>=sum)
sum=newSum;
}
System.out.println(sum);
}
}
My code outputs this number:
2091059712
Your code makes a cast to long too late: by the time the cast is performed, the multiplication has been completed in 32-bit integers, predictably causing an overflow.
Change the code as follows to fix the problem:
// newSum should be called newProd, because you use multiplication, not addition
newSum= ((long)n1)*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13;
Note that your algorithm is not the most efficient: you could do it 13 times faster if you observe that the product for positions i+1..i+13 can be computed from the product for positions i..i+12 by dividing the value at position i and multiplying by the value at position i+13.
Of course you would have to be careful not to divide by zero. You can work around this by observing that any time you encounter a zero, the next 13 products would all be zero, so you could simply skip them, and move on to the next "train" of non-zeros.
The problem is that n1*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13 overflows because:
they are all int variables, and
an int multiplied by an int gives an int.
The typecase to long is applied to the entire product, and (therefore) happens too late to cause the computations to be done with long arithmetic and avoid the overflow problem.
The simple solution to that particular problem is to declare the n variables as long. It is possible that #dasblinkelights' code (casting n1) is faster ... but you would need to benchmark it to be sure. And there are more significant optimizations than that.
I get the answer as 23514624000 . which is actually correct.
public class LargestProduct {
public static void main(String[]args) {
String s="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
long k=0,l=13,ans=1,n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13;
long Max_Num=0;
String[] result=new String[1000];
result=s.split("");
for(int i=0;i<=987;i++) {
n1=Integer.parseInt(result[i]);
n2=Integer.parseInt(result[i+1]);
n3=Integer.parseInt(result[i+2]);
n4=Integer.parseInt(result[i+3]);
n5=Integer.parseInt(result[i+4]);
n6=Integer.parseInt(result[i+5]);
n7=Integer.parseInt(result[i+6]);
n8=Integer.parseInt(result[i+7]);
n9=Integer.parseInt(result[i+8]);
n10=Integer.parseInt(result[i+9]);
n11=Integer.parseInt(result[i+10]);
n12=Integer.parseInt(result[i+11]);
n13=Integer.parseInt(result[i+12]);
ans=n1*n2*n3*n4*n5*n6*n7*n8*n9*n10*n11*n12*n13;
Max_Num=Math.max(Max_Num, ans);
}
System.out.println(Max_Num);
}
}
I have an array of ints ie. [1,2,3,4,5] . Each row corresponds to decimal value, so 5 is 1's, 4 is 10's, 3 is 100's which gives value of 12345 that I calculate and store as long.
This is the function :
public long valueOf(int[]x) {
int multiplier = 1;
value = 0;
for (int i=x.length-1; i >=0; i--) {
value += x[i]*multiplier;
multiplier *= 10;
}
return value;
}
Now I would like to check if value of other int[] does not exceed long before I will calculate its value with valueOf(). How to check it ?
Should I use table.length or maybe convert it to String and send to
public Long(String s) ?
Or maybe just add exception to throw in the valueOf() function ?
I hope you know that this is a horrible way to store large integers: just use BigInteger.
But if you really want to check for exceeding some value, just make sure the length of the array is less than or equal to 19. Then you could compare each cell individually with the value in Long.MAX_VALUE. Or you could just use BigInteger.
Short answer: All longs fit in 18 digits. So if you know that there are no leading zeros, then just check x.length<=18. If you might have leading zeros, you'll have to loop through the array to count how many and adjust accordingly.
A flaw to this is that some 19-digit numbers are valid longs, namely those less than, I believe it comes to, 9223372036854775807. So if you wanted to be truly precise, you'd have to say length>19 is bad, length<19 is good, length==19 you'd have to check digit-by-digit. Depending on what you're up to, rejecting a subset of numbers that would really work might be acceptable.
As others have implied, the bigger question is: Why are you doing this? If this is some sort of data conversion where you're getting numbers as a string of digits from some external source and need to convert this to a long, cool. If you're trying to create a class to handle numbers bigger than will fit in a long, what you're doing is both inefficient and unnecessary. Inefficient because you could pack much more than one decimal digit into an int, and doing so would give all sorts of storage and performance improvements. Unnecessary because BigInteger already does this. Why not just use BigInteger?
Of course if it's a homework problem, that's a different story.
Are you guaranteed that every value of x will be nonnegative?
If so, you could do this:
public long valueOf(int[]x) {
int multiplier = 1;
long value = 0; // Note that you need the type here, which you did not have
for (int i=x.length-1; i >=0; i--) {
next_val = x[i]*multiplier;
if (Long.MAX_LONG - next_val < value) {
// Error-handling code here, however you
// want to handle this case.
} else {
value += next_val
}
multiplier *= 10;
}
return value;
}
Of course, BigInteger would make this much simpler. But I don't know what your problem specs are.