Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am missing the prime numbers, 2 and 3 from the output.
public static ArrayList<Integer> findPrimes(int n){
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i < n; i++){
for(int x = i - 1; x > 2; x--)
if(i % x == 0)
break;
else if(x == 3 && i != 4)
primes.add(i);
}
return primes;
}
When I put n = 72, it prints good, but 2 and 3 are not being output. I have no clue why it keeps printing that. Any help would be great. As shown below.
Output:
Prime numbers: 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
Thanks! If you have another way, feel free to throw out, something I can learn from. Thanks a lot!
Your code explains the problem. The second for loop will terminate before it's executed even once due to the conditional always being false for values 3 and below.
First loop run: i = 2, x = 1, 1 is not more than 2, so the loop does not run.
Second run: i = 3, x = 2, 2 is not more than 2, so once again, same priblem.
When i=2 or i=3, x would initialise to 1 or 2, hence it will never enter the nested for loop (because x>2 is not fulfilled), thus primes.add(i) will not get executed.
Hint: A better way to print prime numbers 2...N is to use sieve approach: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Edit: After re-evaluation, I've realized your logic is a bit off throughout. The code should actually read:
for (int i = 2; i < n; i++){
for(int x = 2; x <= i; x++)
if(i == x)
primes.add(i);
else if(i % x == 0)
break;
}
After testing this, it appears to work correctly.
When i = 2 or 3, x is < 2 and the inner for loop doesn't execute.
I'd change x to count up from 2:
for (int i = 2; i < n; i++){
for(int x = 2; x <= i; x++)
if( x == i)
primes.add(i);
else if (i % x == 0)
break;
}
return primes;
}
Typing this out on an iphone is terrible.
Inner for loop won't execute values less than 2. So, you have to initialize x =2; in inner for loop.
for(int x = 2; x <= i; x++)
Try this.
Related
i'm just started to learn java yesterday. But, now i met difficulty to show the arithmetic progression like the display below:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
From that example, i know that every odd numbers, the numbers increment. I've tried to make it, but the display just keep showing like this:
2 4 4 4 6 6 6 6 6 8 8 8 8 8 8 8 10 10 10 10 10 10 10 10 10
Here's my code:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print(i + " ");
}
}
}
And then, i want to take the last value of it. For example, if i have row = 3, it must be value = 2.
because :
row = 1 2 3 4 5 6 7 8 9 10
value = 1 2 2 2 3 3 3 3 3 4
Would you tell me, what line is exactly must be fix? Thank you
It's not about a line that is wrong, it's your approach that's a bit off. You could fix it in multiple ways. Easiest (but not most efficient) way is this:
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
for(int j = 1; j<i; j++){
System.out.print((i/2) + " ");
}
}
}
As you can see, only the output was changed and now it works. However, iterating over 11 numbers (0-10) when you only really care about 4-5 is not necessarily the best way to go here.
It also doesn't make your code easy to understand.
Here's an alternative.
int amount = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < amount; j++) {
System.out.print(i + " ");
}
amount = amount + 2;
}
Here you can see that the outer for has been changed to only take the numbers we actually care about, which means we can remove the if completely.
We just have to somehow decide how many times we want to execute the print call, which is done with the amount variable.
Try this.
for (int i = 1, r = 1; i <= 4; ++i, r += 2)
System.out.print((i + " ").repeat(r));
You can calculate value from row with this method.
static int value(int row) {
return (int)Math.ceil(Math.sqrt(row));
}
So you can also do like this.
for (int row = 1; row <= 16; ++row)
System.out.print(value(row) + " ");
result:
1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4
Hey it's a representation of a sequence that grows by 2 every step.
i.e the first element is 1 which shows up one time.
the second element is 3 which shows up 3 times (2 2 2)
and so on and on..
so the code you need is:
int a = 1;
for(int i=1; i<=10;i++){
int j=1;
while(j<=a){
System.out.print(i);
j++;
}
a+=2;
}
printing the value in a wanted row:
Scanner in = new Scanner(System.in);
int rowU = in.nextInt(); // User inputs row
int row = 1; // a variable to keep track of the rows
int repeats = 1; // the number of times a value shoud appear
for(int value=1;value<=10;value++){
int j=1;
while(j<=repeats){
if(row==rowU) // if we got to the wanted row
System.out.println(value); // print the wanted value
j++;
row++;
}
repeats+=2;
}
There is a better, more efficient way to get the value of a wanted row:
int wanted_value = Math.ceil(Math.sqrt(wanted_row));
Thanks to #saka for bringing this one up!
Hope I helped :)
i % 2 == 0 means that the following code is only going to be executed, if i is even.
You could try removing the if, and change the second for to something like
int j = 0; j < 2 * i - 1; j++.
This code snippet will do the work
int n=4;
int printTimes=1;
for(int i=1;i<=n;i++)
{
for(int j=0;j<printTimes;j++)
System.out.print(i+" ");
printTimes+=2;
}
System.out.println();
Here is the example code.
int start = 1;
int end = 5;
int time = 1;
for (int i = start,j = time; i < end; i++,j+=2) {
for (int k = 0; k < j; k++) {
System.out.print(i+" ");
}
}
My problem is that my code works perfectly when executed on an IDE But it exceeds the the time limit on Spoj. I am not getting any hint on how to make it more efficient.Spoj challenge
Here is my code :
import java.util.Scanner;
public class Factorial {
public static int getDecomposition(int a) {
int count = 0;
int result = a;
while (result % 5 == 0) {
result /= 5;
count++;
}
return count;
}
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
int sum[] = new int[testCases];
int nums[] = new int[testCases];
for (int i = 0; i < testCases; i++) {
nums[i] = scan.nextInt();
}
for (int i = 0; i < testCases; i++) {
for (int j = 5; j <= nums[i]; j = j + 5) {
sum[i] += getDecomposition(j);
}
System.out.println(sum[i]);
}
}
}
I’m thinking: Take 60 as an example (this is one of the example inputs in the linked challenges). You are correct in the assumption in your code that for each number from 1 to 60 you only need to consider how many times it’s divisible by 5, since there will always be enough numbers divisible by 2 that you will have this many zeroes. So how many of the numbers from 1 through 60 are divisible once by 5? Answer: 60 / 5 = 12. Out of those 12, how many are divisible by 5 once more? 12 / 5 = 2 (ignore any remainder). Add the 12 and the 2 (= 14) to record that until now we know that the factorial of 60 is divisible by 5 14 times. And out of those 2, how many are divisible a third time? 2 / 5 = 0. Once we’ve reached 0, we’re done. The answer was 14 (this agrees with the answer in the example in the link).
So make an algorithm out of this way of finding the answer. I think it will be somewhat faster than the program you have posted.
It may also be that you can find a not too complicated formula for the sum I am calculating so you can avoid looping altogether. And maybe you can find some inspiration here: Geometric progression.
Problem Statement:
Find the minimum number of steps required to reach a target number x from 0 (zero), using only two operations: +1 (add 1 to the number) or *2 (multiply 2 with the number).
So here's the Logic that I came up with:
The best way is to work backwards. Start from the number you need:
Subtract 1 if the number is odd.
Divide by 2 if the number if even.
Stop when you get to zero.
For example, for 29, you get 28, 14, 7, 6, 3, 2, 1, 0.
And, here's what I have tried doing (Java 7):
kValues is an array that has the x values for which the steps are needed to be computed and stored in an array called result.
static int[] countOperationsToK(long[] kValues) {
int size = kValues.length,x,i,steps;
int result[] = new int[size];
for (i = 0; i < size; ++i)
{
steps = 0;
for (x = (int)kValues[i]; x != 0 ; ++steps)
{
if((x % 2) == 0)
x /= 2;
else x--;
}
result[i] = steps;
}
return result;
}
My Problem:
This is a Hackerrank question and I am supposed to write an efficient code. I was successful with 7/11 test cases and others were timed out. Since, it is a Hackerrank question, I can't change the function definition or the return type. That is the reason why I am converting from long to int in my for loop, in order to use % (modulus). I would like to know where I am going wrong. Is my algorithm taking too long to compute (for the number of values close to a million)? Which is obviously the case, but how do I alter my algorithm in order to pass all the test cases?
Thank you in advance :)
for (x = (int)kValues[i]; x != 0 ; ++steps)
The fact that you are casting a long to an int is very suspicious. You might get a negative number when you do that.
Say x == -2: you divide it by 2 to give -1, then subtract 1 to give -2. You'll keep doing that indefinitely.
Just define x to be a long, and remove the cast.
So, here's the working code. I had forgotten to append L while using the modulo. Silly mistake led to so much of typing. LOL!!
static int[] countOperationsToK(long[] kValues) {
int size = kValues.length,i,steps;
int result[] = new int[size];
long x;
for (i = 0; i < size; ++i)
{
steps = 0;
for (x = kValues[i]; x != 0 ; ++steps)
{
if((x % 2L) == 0)
x /= 2L;
else x -= 1L;
}
result[i] = steps;
}
return result;
}
Here is a very short version, using bit-analysis:
static int[] countOperationsToK(long... input) {
int result[] = new int[input.length];
for (int i = 0; i < input.length; i++)
if (input[i] > 0)
result[i] = Long.bitCount(input[i]) + 63 - Long.numberOfLeadingZeros(input[i]);
return result;
}
The idea here is to look at the binary number, e.g. for 29 that is 11101. There are 4 bits set, so we'd need to do +1 four times, and the highest bit position is 4, so we need to left-shift (i.e. *2) four times, for a total of 8 operations: +1, *2, +1, *2, +1, *2, *2, +1.
numberOfBits = Long.bitCount(x)
highBitNumber = floor(log2(x)) = 63 - Long.numberOfLeadingZeros(x)
The highBitNumber part doesn't work if value is zero, hence the if statement.
For input number x,
Minimum no. of Ops = (int)log2(x) + Long.BitCount(x)
So I'm working on Java Koans and I'm stuck on number 69. Here's the code:
#Koan
public void forLoopContinueLabel() {
int count = 0;
outerLabel:
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
count++;
if (count > 2) {
continue outerLabel;
}
}
count += 10;
}
// What does continue with a label mean?
// What gets executed? Where does the program flow continue?
assertEquals(count, __);
}
assertEquals checks if the answer is correct - it sends Koans both arguments and if they match you advance. For example, if one wrote assertEquals(3 + 3, 6) it would be correct.
The double-underscores mean REPLACE ME. In the Koans application it says that I need to replace the underscores with 8, but I don't understand exactly how the continue outerLabel works.
So my question is: Why is count 8?
Thanks in advance. Any help would be appreciated.
Only for i is 0 the j is 0, 1, 2.
For the remaining 5 i's only j is 0
1*3 + 5*1 = 8
Or
i j count
= = =====
0 0 0 count++
1 count++
1 2 count++
2 3 count++; continue outerLabel
1 0 4 count++; continue outerLabel
: : : :
5 0 8 count++; continue outerLabel
continue outerLabel; force to skip the second for.
Although the second for intends to iterate 6 times, it actually iterate only 3 times when i==0 and once for i>0.
What I have done here is taken the contents of the table below and stored them in a list called tableElems
0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35
List<WebElement> tableElems = chrome.findElements(By.tagName("td"));
From this table I want to print in a pattern starting at the 4th element (#3 in the table) and I want to print 3 elements, then skip the next 6, print the next 3 and then skip the next 6, etc. etc.
So my expected output would be 3 4 5 12 13 14 21 22 23 30 31 32
My initial attempt ended with
for (int i = 3; i<tableElems.size(); i++) {
if(i % 3 == 0) { System.out.println(tableElems.get(i).getText()); }
else if(i % 4 == 0) { System.out.println(tableElems.get(i).getText()); }
else if(i % 5 == 0) { System.out.println(tableElems.get(i).getText()); }
}
Obviously this is wrong, because my % 3 will print the 9th element, % 4 will print the 16th element, etc.
I am having trouble wrapping my head around this, so any advice to point me in the right direction is appreciated!
try this:
for (int i = 3; i<tableElems.size(); i++) {
if (((i / 3) % 3) == 1) { System.out.println(tableElems.get(i).getText()); }
}
Think about this as dividing into groups of nine, and further dividing each group of 9 into groups of 3. on the second group of 3 (i.e. 3-5, 12-14) it will display.
int offset = 4;
int width = 3;
advice:
for each row in table check offset + width is under the row width, and then start from offset + 0, offset + 1 upto offset + width
and continue this loop for all the row of table
You mentioned that tableElems is a list, so I assume it's akin to a single-dimension array, rather than what appears to be a multi-dimensional table like you've laid out(I assume for visual purposes).
You're right by starting the for loop at i = 3. The easiest way, IMO, to do this is to just bump the loop ahead several spaces in the array after you've printed three elements. Here's my solution using C# and an array; you should be able to convert it to Java pretty easily.
int counter = 0;
for (int i = 3; i < array.Length; i++)
{
if (counter < 3)
{
Console.WriteLine(array[i]);
counter++;
}
else
{
i += 5; // we are incrementing by one on the next pass, so this can be 5
counter = 0;
}
}
If you want to stick to %, then this should work
int rowSize = 9;
for (int i = 0; i < tableElems.size(); i++) {
int column = i % rowSize;
if (column >=3 && column <= 5) {
System.out.println(tableElems.get(i).getText());
}
}
Update: Java code
for (int i = 3; i<tableElems.size(); i += 9) {
System.out.println(tableElems.get(i).getText());
System.out.println(tableElems.get(i+1).getText());
System.out.println(tableElems.get(i+2).getText());
System.out.println(tableElems.get(i+3).getText());
}
If you are creating a larger pattern:
int starting = 3;
int nextStartDistance = 9;
int waveCount = 3;
for (int i = starting; i<tableElems.size(); i += nextStartDistance) {
for (int b = 0; b <= waveCount; b ++) {
System.out.println(tableElems.get(i).getText());
}
}
This code is written in JavaScript, but the algorithm considered:
var list =[
0,1,2,3,4,5,6,7,8,
9,10,11,12,13,14,15,16,17,
18,19,20,21,22,23,24,25,26,
27,28,29,30,31,32,33,34,35];
for (var index = 3; index <= list.length; index +=9 ) {
var a = list[index];
var b = list[index+1];
var c = list[index+2];
var d = list[index+3];
console.log(a,b,c,d);
}
Result will be what you expected:
// 3 4 5 6
// 12 13 14 15
// 21 22 23 24
// 30 31 32 33
// user:~$
for (int i = 3; i < tableElems.size(); i += 9) {
for (int j = i; j < i + 3 && j < tableElems.size(); j++) {
System.out.println(tableElems.get(j).getText());
}
}
i think this would be very close to your code:
for (int i = 3; i < tableElems.size(); i++) {
if (i % 3 == 0) {
System.out.println(tableElems.get(i).getText());
} else if ((i % 3) == 1) {
System.out.println(tableElems.get(i).getText());
} else if ((i % 3) == 2) {
System.out.println(tableElems.get(i).getText());
i = i + 6;
}
}
i just adapted your modulo and skip 6 elements every time i hit the last one to print out
furthermore its quite effective because all unneeded elements are just skipped instead of iterated and checked
Assuming you only care about the values out of your table and the html structure is standard html tags as shown on your questions, then you can use css selector to select appropriate values.
chrome.findElements(By.cssSelector("td:nth-child(4),td:nth-child(5), td:nth-child(6)"))
Please note that css nth-child selector is 1 based.