Reputation: 1316
I've to print a number which is a huge sequence of 5's and 3's (upto 100,000 ints). Instead of storing it in array, I just kept their count in noOfThrees
and noOfFives
.
For simplicity call this number x
. .
Since I have to print the largest number in the sequence, x
will be initially 5's and then followed with 3's (I have working logic to print if there's no 5's or no 3's)
To print the number, I am using a for loop like this :
for(int i=0; i<noOfFives; i++)
System.out.print(5);
for(int i=0; i<noOfThrees; i++)
System.out.print(3);
But if x
is a 100,000 long int number, it takes about 4-5sec to print it on console which is not desirable.
My take:
noOfFives
is even, then print 55
in the for loop which increases the performance by x2 and increment the loop by two, elsenoOfThrees
.But the problem here is if it's odd, it will again end up printing in steps of 1. How do I effectively print this sequence?
Upvotes: 0
Views: 257
Reputation: 140318
If you think that the number of print
calls is the issue, you could reduce it to just 1: put the right number of 3s and 5s into a char array, then print that:
char[] cs = new char[noOfFives + noOfThrees];
Arrays.fill(cs, 0, noOfFives, '5');
Arrays.fill(cs, noOfFives, cs.length, '3');
System.out.print(cs);
Upvotes: 4
Reputation: 96
I think you can use loop unrolling, it can reduce execute time of loop.
for example:
for(int i=0; i<noOfFives; i+=5) {
System.out.print(5);
System.out.print(5);
System.out.print(5);
System.out.print(5);
System.out.print(5);
}
For more details look at https://en.wikipedia.org/wiki/Loop_unrolling
Upvotes: 0
Reputation: 7476
Your question seems a bit strange - I wonder whether the logical way to make your code faster is to look elsewhere at how these values are calculated.
However I think it would significantly increase your performance to first build the string in memory and then print it.
I also think you should look at Why is printing "B" dramatically slower than printing "#"? which might shed some interesting light on your issue.
Upvotes: 1