How would I format a while(loop)? - loops

I'm having trouble understanding the format a while(loop) uses.
How would I go about making one for example one that computes the sum of all multiples of 5 and 9 between a set range of numbers?

while STATEMENT:
CODE BLOCK
The basic format of any while loop is such that "CODE BLOCK" is executed as long as "STATEMENT" holds true.
For example:
x = 6
while (x > 5) and (x < 20):
x = x + 1
As long as x is greater than 5 and less than 20 x will be incremented by one. The loop will terminate when x is equal to twenty. If I had initialized x to 0, the loop would never enter the block and x will remain zero.
Hopefully that helps

Related

Can someone explain the logic of this bit of code?

I ran it through an IDE and the remainder values came out 3, 2, 0, 1.
I understand the first remainder, but not the rest.
Also, how come the loop terminates? Isn't x always going to be greater than 0, therefore continuing indefinitely? Thank you.
int x = 1023;
while (x > 0)
{
printf("%d", x% 10);
x = x /10;
}
Note that in C, when both operands of a division have integer type, the division also has an integer type, and the value is the result of division rounded toward zero.
So in the first iteration, the statement x = x /10; changes x from 1023 to 102 (not 102.3).
since you are dividing integers you are getting rounded results each time,
so each iteration of x becomes
102
10
1
Just print x each time and you will see.
So 102 modulo 10 is 2
10 modul0 10 is 0
1 modulo 10 is 1

Why doesn't this factorial compute correctly?

I am trying to learn some C programming, and to test my basic skills, I am making a simple program that computes factorials. However, instead of giving the correct answer of 120 for the factorial of 5, it gives -1899959296. What's wrong? Here's my code below:
#include <stdio.h>
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
x *= i;
return x;
}
int main()
{
int a = 5, b;
b = factorial(a);
printf("The factorial of %d is %d \n", a, b);
return 0;
}
Thanks in advance!
Your problem is that the function factorial() is continually modifying x. For any of x which is initially 3 or more, x will keep increasing, so the loop will keep running.
Consider if you call fact(3).
The function is called with x = 3. First iteration of the loop with i = 1 will multiply x by 1. So x will still have the value of 3. i i will be incremented to 2, which is less than 3, so the next iteration starts.
The second iteration of the loop will multiply x by 2, giving the result of 6. i is incremented to 3, which is less than 6, so the next iteration starts.
The third iteration will multiply x by 3, giving the result of 18. i is incremented to 4, which is less than 18, so the next iteration starts.
Notice the pattern in the above ..... the end condition is i < x. i is incremented in each iteration. x is multiplied by i. This means that x increases substantially faster than i does .... which means i < x is always true.
Well almost ..... eventually the logic breaks down.
Eventually x will overflow - the result of multiplying it by i will produce a result that exceeds what can be stored in an int. The result of overflowing an int is undefined ..... anything can happen at that point.
Compare the description above with what YOU would do if asked to compute the factorial of 3. Would you do similar steps? Probably not.
int factorial(int x)
{
int i;
int count =x;
for(i=1; i < count ; i++)
x *= i;
return x;
}
Modify like this. your issue is with the loop count.. Since value of x is changing the loop may become infinite..
C) You're using x as an upperbound for your for loop i < x
B) You're also increasing x nearly exponentially on every loop x *= i, your loop won't work.
You might have noticed that you get a negative number back. The reason the loop exits at all is that you've chosen to type x as a 32 bit signed integer (the default int)- The processor works in binary: so once you go higher than is actually possible with just 32 bits, it still tries to do math but it loses data and loops back around to negative numbers. So once x loops back around and becomes negative, then i > x and the loop exits.
Here: http://tpcg.io/8sX5ls
The error is in the for, the factorial of a number is n * n-1 * ... * n-(n-1), so to solve this, just start the index in x - 1 and decrement it until it turns 1, sorry for my bad English, I hope you understood what I said.
here is the answer:
for ( i = x - 1; i > 1; --i )
x *= i;
Just to explain why the negative number, first we must understand what happens in the for which it was declared.
for(i=1; i < x; i++)
x *= i;
As we can see the condition for it to continue in the loop is i < x, but within it is assigned to x the value of x * i (x * = i or x = x * i), so x has no constant value and is always increasing, the i increases at a velocity smaller than that of x because the i is always added to 1 (i ++, i + = 1 or i = i + 1), which causes the x to be unreachable , then the for will be in an infinite loop.
But every type has its range, and int is 4 bytes, therefore 32 bit, what happens is that there comes a time when x exceeds this range having the famous integer overflow, this is why its value is negative, then the condition of the for becomes false and then the for stop.
We have to remember that a number is represented in memory in binary form, and the last binary number is what represents whether the number is positive or negative, 0 is positive, 1 is negative, when integer overflow happens the last number changes to 1 , making it so negative.
To better understand this here are some links that can help:
https://en.wikipedia.org/wiki/Two%27s_complement
https://en.wikipedia.org/wiki/Integer_overflow.

What's the time complexity of this while loop?

while(n>x)
x*=x;
The correct answer is log(log(n)), I can see the log(n) since x^k>=n is when the while loop will stop. so I got to log(n), what am I missing?
P.S: it is given that x=2.
Let a be the original value of x, and assume a>1.
After the first cycle, x=a**2
After the second cycle, x=a**4
After the third cycle, x=a**8
... After the k-th cycle, x = a**(2**k)
x >= n means
a**(2**k) >= n
2**k >= log(n)/log(a)
k >= log2(log(n)/log(a)) = log2(log(n))-log2(log(a))
Expand the loop (let x = 2) and you'll see:
x = 2
x = 4 // 2 * 2
x = 16 // 4 * 4
x = 256 // 16 * 16
x = 65536 // 256 * 256
...
x = 2 ** (2 ** n) // you can prove this by induction
and so
n = log(log(x))
you'll be quite right with n = log(x) estimation if you have x *= constant body, e.g. for the constant == 2 we have
x = 2
x = 4
x = 8
...
x == 2 ** n
where n is just
n = log(x)
Let x starting value be a, > 1. Each time the value of x is an exponential of a, and the exponential doubles each time, as you are squaring the number each iteration.
So the m'th term is given by , where m is the number of loops executed. Therefore we need , or , which is indeed .
Edit: (Given x = 2)
Your answer would be correct if:
while(n>x)
x*=2;
This means the time to reach the result is cut into half every iteration.
But since the time is cut by x every iteration and x is increasing, you'll get O log(Log(n)).
Log(n) is the complexity where you skip half the way every iteration (B-Tree).

Unclear about modulus function c language

Here is a C language function, which I am having a little trouble understanding. I need to show what values of r come out when I input values of 6 or 10 or 13 into the function:
int factor(int val){
int r=val-1;
while(val%r){
r--;
}
return r;
}
I'm not sure if I misunderstood the question but wouldn't the remainder always be true? Since 0 = false and the while statement never reaches 0 because r is always smaller than val and not equal to it, and each time r decreases the remainder just gets bigger?
Edit: Just realized i forgot to account that 6%3 = 0! thanks for the help people who helped!
Test for yourself: 4 % 2.
The result should be 0 as the % operator returns the remainder of a division.
while(x % y) {} translates in this context to something like: as long as x is not dividable by y, do something, whereby 'do something' is decrease y in your case.
Essentially, the function returns the largest factor of the number input to the method.
It translates to "while there is a remainder from division (r is NOT a factor of val), decrease r by 1 and check again. Once the clean factor is found (val % r is 0), return the factor (r).
Here's a JavaScript port with sample output:
http://jsfiddle.net/43HxX/2/
I rewrote it in JS and you can uncomment the alert(...) line to see the output for 6, 10, and 13

Using modulus in for loop

I am trying to understand how to repeat loops using the mod operator.
If you have two strings, "abc" and "defgh", how can % be used to loop through abc, repeating it until the end of defgh is reached? Namely, what is the mod relationship of the length of abc and defgh?
I don't really understand this concept.
Simple.
std::string abc("abc");
std::string defgh("defgh");
for (size_t i = 0; i < defgh.length(); ++i)
{
printf("%c", abc[i % abc.length()]);
}
Think about what the Modulus operator is doing, it discretely divides the left hand side by the right hand side, and spits back the integer remainder.
Example:
0 % 3 == 0
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0
4 % 3 == 1
In our case, the left hand side represents the i'th position in "defgh", the right hand represents the length of "abc", and the result the looping index inside "abc".
The typical usage of mod is for generating values inside a fixed range. In this case, you want values that are between 0 and strlen("abc")-1 so that you don't access a position outside "abc".
The general concept you need to keep in mind is that x % N will always return a value between 0 and N-1. In this particular case, we also take advantage of the fact that if you increase x by 1 x % N also increases by 1. See it?
Another important property of modulus that we use here is the fact that it "rolls over". As you increase x by 1, x % N increases by 1. When it hits N-1, the next value will be 0, and so on.
Look at #Daniel's code. It's C++ but the concept is language-agnostic

Resources