my loops problems seems to be running an not stopping
am not getting the loop to stop it running cont and wont stop
rate=interest/100;
double monthly_rate=rate/period;
double n=period*length;
payment = (principal * Math.pow((1 + monthly_rate), n)) / n;
System.out.printf("Test acoount amount is %.2f",payment);
for(double i=payment; n<=n; n++){
System.out.println(i+ "" +(payment-i));
}
n <= n
will generally always be true.
You need to figure out the terminating condition of the loop, and possibly fix the n++ as well. It's likely to be something like:
for (int prd = 1; prd <= n; prd++) ...
which will loop n times with prd holding the values 1 through n inclusive.
Your problem is right there in the for statement itself:
for(double i=payment; n<=n; n++){
in the conditional n<=n
Basically your expression will never evaluate to anything other than what it's set too, because 'n will always equal n'
What you need is for your check to be a different variable or some kind of upper limit that you wish to cut things off at eg:
int max = 10;
for(double i=payment; n<=max; n++){
How you set and / or control max depends on exactly what your trying to achieve.
Related
I have this for loop and I am preparing for an exam. I want to see how many times this loop executes.
without knowing the value of K and somevalue, how can we determine the number of times SMALL is printed. The book answer says it is K-1.
for(int i=2; i<= k; i++)
if(arr[i]< someValue)
System.out.println("SMALL");
If it were simply
for (int i = 0; i < k; i++) {
The loop would run k times since you are starting at 0 but not reaching k
So add 2 to the starting point you get k-2 times
add back in 1 because it is <= and you get k-1 times.
It tends to get a little less obvious when the increment isn't 1
Note: That is how many times the loop will execute. The number of times SMALL will print can't be determined without more information.
in this case somevalue doesn't matter, you can calculate the count of executed loop your self by using another variable, use this:
int count = 0;
for (int i = 2; i <= k; i++) {
if (arr[i] < someValue) {
System.out.println("SMALL");
}
count++;
}
System.out.println("this for loop executed: " + count + " times.");
The question needs more inputs because without the values of arr[] and somevalue, we cannot find the answer.
However, since the loop starts at 2 and runs till its equal to k, we can say that it will run till k times -1 (since loop starts 2 for a <= condition instead of the usual 1), which translates to k-1 executions of the loop.
Still it doesn't guarantee the number of times "SMALL" will be printed. That is only possible if all values in the array arr are less than somevalue
I assume that if I can't convert my while loop into a for loop, then I don't fully understand the concepts here. Here's my working while loop:
(I am trying to implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = Integer.valueOf(scanner.nextLine());
int sum = 0;
int i = 0;
while (i < number) {
i++;
sum += i;
}
System.out.println(sum);
I was looking at this user's answer here: https://stackoverflow.com/a/36023451/11522261
and tried to implement it, but it's not working.
.....
for (i = 0; i < number; i++){
sum += i;
}
System.out.println(sum);
It looks like the conditions of For Init expression statement and ForUpdate are set right, but I'm having trouble understanding the differences here.
Also, it looks like this exercise is trying to teach loops to solve iterative problems. But I suspect that this isn't helping me practice recursion. Perhaps there is a recursive solution to this problem which would be better. Just thinking out loud here. Thanks!
The difference is that in your while loop, you're incrementing i before adding it to sum, but in your for loop, it's after.
If the while is producing the right result, you can adjust your for by starting at 1 instead of 0 and continuing while <= number instead of < number.
For completeness, here's how your current for loop works:
i = 0
If i < number is not true, exit the loop; otherwise, continue to Step 3
sum += i (i is still 0)
i++
Goto Step 2
On the second pass, i < number is 1 < number so still true if number is greater than 1, so you go to Step 3, do sum += i while i is 1, then continue.
Eventually i < number isn't true anymore, and the loop exits.
For problems like this, the best approach is usually to use the debugger built into your IDE to step through the code statement by statement, looking at the values of variables as you go. That can reveal how things work really well. This article may be helpful: How to debug small programs
Since you are incrementing the value of i before adding it to sum in the while loop, the same thing needs to be done in case of for loop as well. Given below is the implementation using the for loop:
for (i = 0; i++ < number; ){
sum += i;
}
System.out.println(sum);
Use <= instead of <. This will solve Your problem, and make sure you understand why will the following code would work. I would recommand you to use a paper and pencil and start writing down the values of i and sum after every iteration.
for (i = 1; i <= number; i++) {
sum += i;
}
I am not sure what I should be focused on when determining Big-O of functions. Sometimes it seems that the incrementing variable 'i' is what determines asymptotic complexity other times it seems like it is user defined 'n' that determines asymptotic complexity.
In example1 it seems that since there is 3 n's being multiplied that will produce a O(n^3) effect. is that right? what effect might the i = i + 1 have on the overall function? And thinking that the print statement will just produce a O(n) effect since it's nested in the loop, and all thing nested get O(n) at the very least. So overall I would guess this is O(n^3) but not entirely sure. Mainly because it's divided by 4. Not sure what effect that might have n^3/4 is that still n^3?
example1:
for (i = 1; i < (n * n * 3 * n + 17) / 4; i = i +1) {
System.out.println("Hello World);
}
For the second example, the first loop is normal, I think it's effect is n + 1 but I don't know why it's n + 1, why the + 1? why not just 'n'? All in all this (I think) will produce a O(n) in the first line. Second line is a boolean, and I am not sure how that is treated or what effect that has on the Big-O. Since it's nested in the loop it is by default O(n). In the worst case if 'i' is even the second loop will run, and now this is a nested for loop therefore it will produce a O(n^2) effect. The print statement by default will be O(n^2) too.
In the else case we have another for, also being nested which mutates the 'n' by multiplying it, not sure here but if those n's weren't being multiplied the nested loop would just be O(n^2) but here we have n^2 already plus the n^2 from it being nested, so this might be O(n^4)?
So maybe in the worst case it will be O(n^4)? Not sure.
example2:
for (i = 0; i < n; i++) {
if (i % 2 == 0) {
for (j = 0; j < n; j++) {
System.out.println("Hey");
} else {
for (j = 0; j < n * n; j++) {
System.out.prtinln("Now");
}
For the last example here there is n being multipled by 10000, so we immediately have an O(n) effect here. Also not sure why this is but I read that i will also effect the loop, and since "i" is i = i * 2 that will make it log_2(n) I have no idea why this is the case though. How could i = i * 2 produce log_2(n). If this is true I am thinking that the loop will maybe be nlog_2(n) because the n is being multipled by 10000, hence O(n) and then i = i * 2 produces log_2(n) so multiplied together they are nlog(n). The x = x + i; I think this is just O(n) but overall won't make much difference.
example3:
for (i = 1; i <= 10000 * n; i = i *2) {
x = x + i;
}
Please help I am very lost on all this.
Thank you
Example 1:
Example 2:
Example 3:
For more, please consult the last couple of slides from here:
http://faculty.kfupm.edu.sa/ics/jauhar/ics202/Unit03_ComplexityAnalysis1.ppt
I know that the following code is considered "Linear or Θ(n)" what I don't understand is how we know that it is.
Assuming that n has been declared appropriately and has been set to a value.
int sum = 0;
for (int i = 0; i < n*2; i++ )
sum++;
Below is an additional loop that is non-linear from what I can tell but again my question is how do we determine possible speeds by seeing only code? Θ complexity, in terms of n, to be more specific.
int sum = 0;
for ( int i = 0; i < n; i++)
for ( int j = i; j < n; j += 2)
sum++;
In your first example you have only one for loop. The i value linearly increases until the condition i<n*2; is met. The execution time of your for loop is linearly dependent on the value of n so its time complexity is O(n) because your i value is directly proportional to n.
In your second example you have nested for loops. The i value is linearly increasing and for each i value the inner for loop executes n/2 times as your variable j is increased by 2 in each iteration. As the outer loop executes n times and inner loop executes n/2 times for each outer loop iteration, the total running time for this example is n*n/2. But usually the constant part of the time is negligible (or sometimes not considered). So we can say its running time is O(n^2).
Coming to the difference of Big O and Theta notation, Big O is used to represent the upper bound for the growth function and Theta is used to represent the tight bound for the growth function. For more info on the difference, refer difference between Big O and Theta notation.
Big O notion can be thought of as given input of size n how many times are each element processed/accessed in the following program?
So for your first example
int sum = 0;
for (int i = 0; i < n*2; i++ )
sum++;
It doesn't matter what size n is. It only matters how many times does the loop run in respect to n. So since this piece of code will loop n*2 times, the running time of it is also n*2. The reason that this is called linear, or O(n) even though it will run n*2 times is because we are interested in the growth of the running time at astronomically large values of n. At that point, the 2 multiplier in front becomes irrelevant, and that's why it is o(n).
int sum = 0;
for ( int i = 0; i < n; i++)
for ( int j = i; j < n; j += 2)
sum++;
In this example, the program will run n*(n/2) times.
n times in the i loop and n/2 times in the j loop
again, since we are interested in the growth of this function at astronomically large values of n, the 1/2 factor for the n becomes irrelevant, making the running time n*n, or n^2
I've got an issue with an assignment that I have requiring the use of arrays. I need to create the Sieve of Eratosthenes algorithm and print out all the prime numbers. I'm quite confused because as far as I can tell, my order of operations is correct. Here is the code:
//Declare the array
boolean numbers [] = new boolean[1000];
int y = 0;
//Declare all numbers as true to begin
for(int i = 2; i < 1000;i++){
numbers[i] = true;
}
//Run loop that increases i and multiplies it by increasing multiples
for (int x = 2; x < 1000; x++) {
//A loop for the increasing multiples; keep those numbers below 1000
//Set any multiple of "x" to false
for(int n = 2; y < 1000; n++){
y = n * x;
numbers[y] = false;
}
}
I first set all the numbers in the array to true. Then the second loop will start "x" at 2, then inside it is a nested loop that will multiply "x" by values of "n" and "n" will continue to increase as long as the product of that multiplication ("y") is below 1000. Once "y" reaches that maximum, "x" will go up one number and the process repeats until all non-prime numbers are set to false.
That was my logic when I made the code, but when I try to run it I get the "ArrayIndexOutOfBoundsException" error. From what I can tell I set everything to stay below 1000 so it shouldn't be going over the array size.
I know its probably not the most efficient algorithm because as "x" increases it will go over numbers it already went over but it was the most simple one I could think of.
Here:
for(int n = 2; y < 1000; n++){
y = n * x;
numbers[y] = false;
}
you first check that y < 1000, and then intialize and use it. This is the wrong way around.
Also, you can get away with running the above loop only when x is prime. This won't affect correctness, but should make your code much faster.