How does this code print same PrimeFactors? - java

This code print the prime factors of a number.
I wanted to know how does it print the same Prime Factor twice
eg: 45 => 3.3.5
// get the number
for(int i = 2; i< number; i++) {
while(number%i == 0) {
System.out.println(i+" ");
number = number/i;
}
}
if(number >2) {
System.out.println(number);
}

The easiest/best way to understand what the code is doing is to run through it. You could try using a debugger on your end, but we can also try to summarize here:
i = 2
nothing happens, because 45 is not divisible by 2
i = 3
the while loop iterates twice, printing 3 twice, and also setting
number = 45 -> 15 -> 5
i = 4
nothing happens, because 45 is not divisible by 4
i = 5
the while loop iterates once, printing 5 once, and setting number = 5 / 5 = 1
At this point, the outer for loop fails, because i = 5 and number = 1.

when i = 3, while loop iterates two times.
In first iteration it will print 3 and update value of number = 15
As number is updated it will again iterate.
In second iteration it will again print 3 and update value of number = 5
now, (5%3 == 0) is not possible so it will not iterate third time.

Related

How to make a +5 (or any +number) jump in array values inside a for loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So i have a column of data which consists of numbers where i have to find 5 instances of the same number.
So ,for example, 8,8,8,8,8,8,8,8,8,9,9,9,5,6,4,7,,6,2,3, etc. In this 8 has occurred 9 times. So i want to increment the count only once because even though there are nine 8's what my code is doing is taking the first 8 and getting the 5 consecutive numbers are incrementing. Then it takes the next 8 and increments the count and so on where the count becomes 5 but i want it to be 1. What i want is the first occurrence of any number to be the base value and take 5 consecutive numbers and increment the count. Then then take the 6th 8 and count if there are 5 consecutive 8's or that specific number or not. So, for example, 8,8,8,8,8,8,9,9,9,9,9,9,9,9,5,5,5,5,5,1,1,2,2,5,4,3,6,7,9,3,4,2,2,2,2,2,1,2,1. In this the count should be 4.
**count=0;
count1=0;
for i=1:length(data)-4
for j=i+1:i+4
if data(i)~=data(j)
count1=0;
break;
else
count1=count1+1;
end
if count1==5 % line 0
count=count+1;
%data(i,1)=data(i+5,1); //line 1 <=comment
%data(i)=data(i+5); //line 2 <=comment
else
continue;
end
end**
If(count_consecutive==5){
count_main=count_main+1; ...
a[i]=a[i+5];// continue for the base value. It should skip all the numbers that were counted in the consecutive count one and take the next number as the base for counting the consecutive numbers}
The logic in any language would be fine as my error is in the logic
Thanks for any help. It would be greatly appreciated :).
Extra Elaboration
So the first one only has 5 consecutive 8's in the manner i specified. Hence the first one will have an output count =1 . In the second one, there are 4 of the 5 consecutive numbers of the same starting number. Hence the output would be 4, Another example i can give is 8,8,8,8,8,8,8,8,8,8(ten 8's),9,9,9,9,4,5,6,4,6,6,6,6,6. In this , the count should be 3 as it has 10 8's which increments the count to 2 and another 5 consecutive 6 which increments count one more time. Total count would be 3.
Now the error is i can't jump the array index from a[i] to a[i+5]. So the first one only has 5 consecutive 8's in the manner i specified. Hence the first one will have an output count =1 . In the second one, there are 4 of the 5 consecutive numbers of the same starting number. Hence the output would be 4, Another example i can give is 8,8,8,8,8,8,8,8,8,8(ten 8's),9,9,9,9,4,5,6,4,6,6,6,6,6. In this , the count should be 3 as it has 10 8's which increments the count to 2 and another 5 consecutive 6 which increments count one more time. Total count would be 3. My problem is that i'm not able to skip/jump the array index from x to x+5 in the for loop when my condition gets satisfied.
I attach the code in Matlab (also works in Octave):
vector = [8,8,8,8,8,8,9,9,9,9,9,9,9,9,5,5,5,5,5,1,1,2,2,5,4,3,6,7,9,3,4,2,2,2,2,2,1,2,1]
count = 1;
result = 0;
for i = 2:length(vector)
if vector(i-1) == vector(i)
count = count+1;
else
count = 1;
end
if count == 5
result = result+1;
count = 1;
end
end
Mainly, you have to count the number of times that a value appears and increase the result if this number of times arrises 5.
It would be simpler to count the length of the subsequence containing the same elements consecutive and as soon as the subsequence is finished, to increment the resulting counter by the number of groups consisting of N elements in the subsequence: result += consecutive / n:
public static int countConsecutiveN(int n, int ... arr) {
if (null == arr || arr.length < n) {
return 0;
}
int result = 0;
int previous = arr[0];
int consecutive = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == previous) {
consecutive++;
} else { // consecutive sequence ended
result += consecutive / n; // increment by the count of N elements in the subsequence
consecutive = 1;
}
previous = arr[i];
}
// check the trailing subsequence
result += consecutive / n;
return result;
}
Test
System.out.println(countConsecutiveN(5,
8,8,8,8,8,8, // six 8s
9,9,9,9,9,9,9,9,9,9, // ten 9s - 2 groups
5,5,5,5,5, // five 5s
1,1,2,2,5,4,3,6,7,9,3,4,
2,2,2,2,2,2,2, // seven 2s
1,2,
1,1,1,1,1,1 // six 1s
));
Output
6
If you want to count runs of equal values with a minimum length N, in Matlab this can be done very easily with diff (consecutive differences) and find (indices of nonzero entries):
N = 5; % mininum desired run length
x = [8,8,8,8,8,8,9,9,9,9,9,9,9,9,5,5,5,5,5,1,1,2,2,5,4,3,6,7,9,3,4,2,2,2,2,2,1,2,1];
result = sum(diff(find([true diff(x)]))>=N);
If a run ends immediately when reaching length N (so for example 11 consecutive equal values count as two runs of length N=5):
result = sum(floor(diff(find([true diff(x)]))/N));

why does the for loop run twice only

i do not understand why the for loop runs twice, the first value to be printed should be 2 and the last value should be 16 and not 4 since 4 is still less than 10
i have done a for loop that increments the initial value by one but i have not tried to increment the initial value by multiplying it by the first value
for (int i = 2; i <10; i = i*i) {
System.out.println(i);
}
i expected it to run 4 times but it ran just two times
Your loop is equivalent to this:
int i = 2; // Initializer
while (i < 10) // Condition
{
System.out.println(i);
i = i * i; // Update part
}
Note how it will never enter the body of the loop when i is 10 or greater - so it will never print 16.
In other words, the execution looks like this:
Set i to 2.
Check: is i less than 10? Yes, so enter the body of the loop.
Print i.
Set i = i * i, so it's now 4.
Check: is i less than 10? Yes, so enter the body of the loop.
Print i.
Set i = i * i, so it's now 16.
Check: is i less than 10? No, so finish.
Finding what your code is doing is easy with a paper sheet and a pen...
first run, i = 2 -> i < 10 == true -> print 2
second run, i = 2*2 = 4 -> i < 10 == true -> print 4
third run, i = 4*4 = 16 -> i < 10 == false -> out
I try to explain how works for.
1) You initialized variable i = 2
2) Check i < 10
3) Print(i) = 2
--- NEXT ----
1) i = i*i (2*2) = 4
2) Check i < 10 = 4<10 = true
3) Print(i) = 4
--- NEXT ----
1) i = i*i (4*4) = 16
2) Check i < 10 = 16<10 = false
3) EXIT
First time i = 2, loop ran
second time i = 4, loop ran
third time i = 16, loop failed => break
Welcome to stackoverflow. For these cases you should learn to debug your code for better self understanding
You are squaring. 2,4,16 but 16 is greater than i<10 so it does not do that
Because of i = i*i
i = 2
1. i = 2*2 = 4 (4 < 10)
2. i = 4 * 2 = 8 (8 < 10)
3. i = 8 * 2 = 16 (16 > 10)

Nested for loop output printing and formatting incorrect table, it's all funky

So the goal was to use a nested for loop to output 6 rows and 10 columns. The thing was though that the inner for loop was supposed to check to see whether the number was even or odd as, if it was even, we would add 2 to it and then print out that number 10 times before moving onto the next output. So this is what were were supposed to get
1 1 1 1 1 1 1 1 1 1
4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3
6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5
8 8 8 8 8 8 8 8 8 8
I thought I was on the right track but my output is a complete mess, here's what I have. Thank you to anyone willing to help.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 1; nestedE < 10; nestedE++)
{
if (numberE%2 == 0)
{
numberE += 2;
System.out.printf("%2d", numberE);
} else {
System.out.printf("%2d", numberE);
}
}
System.out.printf("%2d\n", numberE);
}
well to start with your inner loop will only iterate nine times. second you don't need a nested loop, you need one loop and a guard determining when to print.
Don't modify numberE inside the loops. Instead just print numberE + 2.
Also, if your inner loop runs from 0 to <10 you will get 10 iterations and you don't need to print the number again - just a newline.
for (int numberE = 1; numberE <= 6; numberE++)
{
for (int nestedE = 0; nestedE < 10; nestedE++) // <-- start at 0 and end <10 for 10 iterations
{
if (numberE%2 == 0)
{
System.out.printf("%2d", numberE + 2); // <-- print the number + 2
} else {
System.out.printf("%2d", numberE);
}
}
System.out.println(); // <-- don't print the value again here
}
I would do it this way. Gives the required result.
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 6; i++)
{
int temp = i;
if(temp%2 == 0) {
temp +=2;
}
for(int j=1;j<=10;j++) {
System.out.print(temp+" ");
}
System.out.println();
}
}
}
A brief description of what is happening here:
So, since we need 6 rows, we use the value of 6 as a row counter. The variable i takes care of keeping a count of the rows. Here since the target is 6, we start from row number 1 and go until row no 6. Inside each value of the loop, we save the value of i to temp because we don't want the value of i to change before incrementing in the main for loop. We then check if this temp value is even by doing a modulo division by 2. If it is even, we increment the temp value by 2.
Then, we run a loop from 1 to 10 since we need 10 columns to print the value temp(either the original i or incremented because it was even). After exiting the loop, finally to move to the next row, we do a System.out.println().
I would suggest using a temporary variable to store the current intended value.
The issue with your solution was that you were modifying the value of numberE by using numberE += 2; inside the second for loop, this changes the value globally.
Moving the final column in to the nested for loops also makes it easier as you wouldn't need to define the temporary variable outside of the loop. Using this also meant changing the <10 to <=10.
for (int numberE = 1; numberE <= 6; numberE++) {
for (int nestedE = 1; nestedE <= 10; nestedE++) {
int current = (numberE % 2 == 0) ? numberE + 2 : numberE;
System.out.printf("%2d", current);
}
System.out.printf("\n");
}
You were pretty close though, with practise you'll get better.

Syntax and Variable Declaration in Nested Loops: How Does an Inner Declaration take Precedence?

I was following an example of how to produce a script in java that computes and prints the powers of 2 (2, 4, 8, 16...) and the script looks like this:
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
}
}
}
The output is:
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
My question is that if the result variable is declared as 1 within the initial for loop but outside the inner while loop, how come its value doesn't reset to 1 every time the for loop runs? It's clear to me that the for loop begins running before the while loop takes over, because the System.out.println() command is run every time. What is it about Java's structure that allows this?
You are absolutely right about result being reset to 1 in each iteration of the for loop. It does get reset.
"But why doesn't printing result give me 2 every time" you ask.
After result is being set to 1, and before that iteration of the for loop ends, the while loop runs. How many times does the while loop runs? It depends on i. In the first iteration of the for loop, the while loop loops once, in the second iteration of the for loop, the while loop loops twice, in the third iteration of the for loop, the while loop loops three times, and so on.
At the end of each iteration of the for loop, result will contain the value of 2 to the power <however many times the while loop looped for>. So at the end of the first iteration of the for loop, result is 2 because the while loop looped only once. At the end of the second iteration, result is 4 because the while loop ran twice and so result *= 2 is ran twice.
If result isn't reset, it would have become 8 by the end of the second iteration of the for loop: it got multiplied once in the first iteration, and twice in the second iteration.
please check below inline explanations
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i = 1; i < 10; i++) {
result = 1; //why doesn't this reset result to 1 for every iteration?
// Yes , result will be 1 always here, you can print the result variable before while as below
// System.out.println("Result : " + result);
e = i;
while(e > 0) {
result *= 2;
e --;
}
System.out.println("2 to the " + i + " power is " + result);
//I would expect printing "result" here would result in 2 every time...
// here the value of result will be decided based on e, here we are multiplying result with 2 , "e" no.of times
}
}
}

Trying To Understand The For Loop Completely

I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates.
Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below.
public class Test {
public static void main (String[] args) {
int sum = 0;
for (int k = 1; k < 10; k += 2)
{
sum += k;
System.out.print(sum + " ");
}
}
}
The output the program puts out is 1 4 9 16 25
Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3?
It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about.
My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around.
Overall my question is, how is sum equal to 1 when k is actually equal to 3.
The sections of the for loop are run at different times.
The first section is run once at the start to initialize the variables.
The second is run each time around the loop at the START of the loop to say whether to exit or not.
The final section is run each time around the loop at the END of the loop.
All sections are optional and can just be left blank if you want.
You can also depict a for loop as a while loop:
for (A;B;C) {
D;
}
is the same as:
A;
while (B) {
D;
C;
}
Let's step through your code:
We setup an int with initial value of 0 and assign it to sum.
We setup a for loop, setting int k = 1, and we will loop while k is less than 10, and after each iteration, 2 will be added to k.
So, the first iteration, k = 1. sum currently equals 0, so sum += k is actually 0 = 0 + 1 = 1. There's the 1 you are getting.
For the second iteration, k = 3. sum currently equals 1, so sum += k is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up.
Repeat this for the rest of the loop!
In the first iteration of the loop, k=1. The k+=2 is only run at the beginning of the next iteration of the loop. The loop variable update condition (the last part of the for loop - i.e. the k+=2 part) never runs on the first iteration but does run on every other one, at the start. Therefore what you have is:
Iteration 1:
k=1
sum = 0 + 1; //so sum = 1
Iteration 2:
k=1+2 // so k=3
sum = 1 + 3 // so sum = 4
Iteration 3:
k=3+2 //k=5
sum = 4 + 5 //sum=9
etc...
It goes like this:
Initialize (k = 1)
Check condition (k < 10) (stop if false)
Run the code in the loop (sum += k and print)
Increment (k += 2)
Repeat from step 2
Following this logic, you get that 1 is printed first.
The last condition, k += 2 occurs after the first iteration of the loop.
So it's
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
k is only incremented after the loop iteration. In general for any loop the values are updated after a loop iteration so k goes 1,3,5,7,9 and so the sum is correct.
Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more.
The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop'
So this is how it starts, its starts with what you set 'k' for which is 1.
k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So
sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has.
So k = 1 + 2 = 3. And now we start the second loop.
k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues.
oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard...
Good luck!
has to
Let's break up your code. The keyword for just means loop. It will start # 1 and continue as long as k is less than 10. It will also increase by k+=2. To translate, it means k = k +2
Inside the loop sum = sum + k. It will then print the value that sum has plus a space.
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
and keep repeating. Let me know if you still have trouble grasping this concept

Categories