Operators evaluation - c++

This code evaluates to true:
#include <iostream>
int main(){
int x = 9;
int j = x-1;
if(x - j+1 > 1)
std::cout << "Ehhhh???\n";
}
But this one to false:
#include <iostream>
int main(){
int x = 9;
int j = x-1;
if(x - (j+1) > 1)
std::cout << "Ehhhh???\n";
}
plus and minus operators has higher precedence than "<", I'm also using only one data type so there should be bo overflow. Why results are different?

This is really just a matter what value the 1 gets added to. Addition and subtraction have left to right associativity so we start from the left and work our way right.
x - j + 1
(9 - 8) + 1
1 + 1
2
Where as
x - (j + 1)
9 - (8 + 1)
9 - 9
0
Forces the addition to be attached to j instead of x-j so the second case is rightly false.

Since the precedence of arithmetic + and - is the same but the associativity is from left to right, the one without the parenthesis will first do the subtraction then the addition, i.e.:
x - j+1 ==2 //here the operation is performed from left to right,subtraction first then addition
x - (j+1)==0 //here the one inside the parenthesis will be done first,i.e addition first then subtraction

Mathematically you have 2 different expressions:
x - j + 1 is equal to x - ( j - 1 )
and
x - ( j + 1 ) is equal to x - j - 1

Related

Optimization. How to speed up the given C ++ code?

This is my code. 1<=i<=j<=n j-i<=a 1<=n<=1000000 0<=a<=1000000
#include <iostream>
using namespace std;
int main(){
int n, a, r = 0;
cin>>n>>a;
for(int i = 1; i <= n; i++){
int j = i;
for(j; j <= n; j++){
if(j-i<=a){
r++;
}
}
}
cout<<r;
}
Instead of loops, I changed it to a simple check of variables, which greatly accelerated the code. there is no need to calculate thousands of options.
My final, optimized code is:
#include <iostream>
using namespace std;
int main(){
unsigned long long n, a, r = 0;
cin>>n>>a;
if(a==0){
r = n;
}
if(n<=a){
r = (n*(n+1))/2;
}
if(n>a){
r += (n-a)*(a+1) + (a*(a+1))/2;
}
cout<<r;
}
After accounting for both positive numbers, negative numbers, and zeros, your double-nested for-loop can be simplified into this:
if (n < 1)
{
r = 0;
}
else if (a == 0)
{
r = n;
}
else if (a < 0)
{
r = 0;
}
else if (n <= a)
{
r = (n * (n + 1)) / 2;
}
else
{
r = (n-a)*(a + 1) + (a * (a + 1)) / 2;
}
Recall that summing a sequence of digits from 1..N is:
N*(N+1)
-------
2
If n <= a (positive numbers), r is incremented n times in the inner loop on the first iteration of the outer loop. Then n-1 times, then n-2 times... all the way down to 1.
For cases where n > a, then there are n-a summations of a+1 followed by a decrementing summation from a down to 1
This strikes me as something to speed up by doing a bit of math, not by massaging the code.
Basically, we can think of the loops as defining a square matrix of the values of i and j. So let's assume n = 9, and a = 3. I'll draw in a + for each place we increment r, a blank for the values we don't generate, and a 0 for the places we generate values, but don't increment r.
i\j 1 2 3 4 5 6 7 8 9
1 + + + + 0 0 0 0 0
2 + + + + 0 0 0 0
3 + + + + 0 0 0
4 + + + + 0 0
5 + + + + 0
6 + + + +
7 + + +
8 + +
9 +
So, ignoring the last a rows (i.e., for the first n-a rows), in each row we have a band a + 1 elements wide where we do an increment. Then at the end, we have a triangle, where we're basically summing a + a-1 + a-2 ... 0.
So, the first piece is (a+1) * (n-a) and the second piece is a * (a+1) / 2. Add those together, and we get the final answer.
Seems like
for(j; j <= n; j++){
if(j-i<=a){
r++;
}
}
could be replaced by
r += f(i,n,a);
Where f() is some simple expression involving those 3 values, probably including the equivalent of min(..,..)
If you want to speed up your code, instead of just tuning your algorithm, you can also try to use some parallel api.
Parallel computing api such as OpenMP enables you take advantage of your cpu resources.
If you uses OpenMP, you can try to use it to parallel your loop.

How to Calculate A to the power B without use of multiplication and divsion operator?

I need to find A raise to the power b, simply power ( a, b ) without the use of multiplication and division operator
Ex: pow ( 2, 3 ) = 8
I am unable to understand the intuition behind this code.
int pow(int a, int b)
{
if (b == 0)
return 1;
int answer = a;
int increment = a;
int i, j;
for(i = 1; i < b; i++)
{
for(j = 1; j < a; j++)
{
answer += increment;
}
increment = answer;
}
return answer;
}
well the inner loop multiplies a by itself by adding it to itself a times.
the outer loop does this b times
It works like this:
If the exponent is zero you just return 1. Otherwise you need to do a calculation.
The inner loop, i.e.
for(j = 1; j < a; j++)
{
answer += increment;
}
performs a multiplication. The result of executing that code is equivalent to
answer += increment * a;
And the outer loop is repeating that multiplication b - 1 times (because answer starts as a, so you need one less multiplication as if you were starting with answer = 1), I.e. in total you get
answer += ((a * a) * a ) ... *a
for b-1 times in total, which is equivalent to a^b.
...power ( a, b ) without the use of multiplication and division
operator
To avoid multiplication, note that 3 x 5 means either
3+3+3+3+3
or
5+5+5.
For power, note that 3 ^ 3 (i.e. 3 cubed) means 3 x 3 x 3. The multiplications in this product can be replaced with additions (i.e. 3 x 3 => 3+3+3, and then 9 x 3 = 9+9+9 = 27).

C++ for with multiple control statements using comma operator

How does comma operator if it is used in a 'for loop' for writing multiple control statements?
i tried
#include <iostream>
using namespace std;
int main() {
for (int x = 0, y = 0; x < 3, y < 4; ++x, ++y) {
cout << x << " " << y << endl;
}
return 0;
}
and it seems like only the last expression is evaluated. Ty
This is how comma operator works. Its 1st operand x < 3 is evaluated, then the result is discarded; then the 2nd operand y < 4 is evaluated and the value is returned as the return value of the comma operator. x < 3 has not any effects here.
You might want to use operator&& or operator|| for this case, e.g. x < 3 && y < 4 or x < 3 || y < 4 based on your intent.

How to find the Nth number in a fractal sequence?

The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...
This is what I've come up with so far:
#include <iostream>
using namespace std;
int main()
{
long long n,k=1,result;
cin >> n;
if(n==1){
result=1;
}else{
for(int i=1,j=1;;i=j,j=j+k){
if(n>i&&n<=j){
result=n-i;
break;
}else{
k++;
}
}
}
cout << result << endl;
}
This is also what I've written before:
#include <iostream>
using namespace std;
int main()
{
long long n,count=0,result;
cin >> n;
for(int i=1;;i++){
for(int j=1;j<=i;j++){
count=count+1;
if(count==n){
result=j;
break;
}
}
if(count>=n){
break;
}
}
cout << result << endl;
}
Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:
1 <= n <= 10^12
So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.
We can group numbers in your sequence:
(1) (1, 2) (1, 2, 3) ...
The overall amount of numbers is
1 + 2 + 3 + ...
The latter is an arithmetic progression, its sum equals to x*(x+1)/2.
We'll find the number of full groups k that go before n+1-th number in the sequence. k equals to the maximal integer such that k*(k+1)/2 <= n. To find it we'll solve the quadratic equation:
x*(x+1)/2 = n
x^2 + x - 2*n = 0
Let's assume that positive root of this equation is x'. We round it down to the nearest integer k. If x' == k (x' is a whole number) it is the answer. Otherwise, the answer is n - k*(k+1)/2.
Exemplary c++ implementation:
double d = 1 + 8.0 * n;
double x = (-1 + sqrt(d)) / 2;
long long k = floor(x);
long long m = k*(k+1) / 2;
if (m == n) {
return k;
} else {
return n - m;
}
The solution has O(1) time complexity.
The first job is to write out the sequence like this:
1
2 3
4 5 6
7 8 9 10
And note that we want to map this to
1
1 2
1 2 3
1 2 3 4
The row position of a number is given by rearranging the formula for an arithmetic progression, solving the resultant quadratic, discarding the negative root, and removing any fractional part of the answer. A number t appears in the row r given by the whole number part
r = R(1/2 + (1/4 + 2 * (t - 1))1/2)
Where R() is a function that rounds a number downwards to the whole number.
But you are after the column c. That is obtained subtracting the value of the first term in that row from t:
c = t - 1/2 * r * (r - 1)
Reference: https://en.wikipedia.org/wiki/Arithmetic_progression
A solution using loop. It will out the number at nth.
x = 0 ;
i = 1 ;
do {
x += i ;
if( x == n ) {
cout<< i ;
break ;
}
else if( x > n ) {
cout<< (n - (x-i)) ;
break ;
}
i ++ ;
}while( 1) ;

Understanding the arithmetic in `(1 << j) - 1`

Would appreciate help in explaining the following bit operation. Pardon my lack of understanding of bit arithmetic.
int max = ~0;
int left = max - ((1 << j) - 1);
What will be the result of this operation? Is (1<<(j-1)) equivalent to ((1 << j) - 1)?
Follow the below formulas,
Case : 1
(1 << j) - 1) is equal to 2^j-1 [j = 1,2...]
Case : 2
(1<<(j-1)) is equal to 2^(j-1) [j = 1,2,3...]
Is (1<<(j-1)) equivalent to ((1 << j) - 1)?
No, Obviously from above formulas.
What will be the result of this operation?
For this question, max will be "-1" [bitwise NOT(0) is equivalent to complement of all bit values of 0]
then formula will be
left = -(2j)
If j = -1 or j = 0, then the above formulas won't work as expected, because 1<<-1 is undefined behavior in C. More details found at below links.
https://stackoverflow.com/a/4945765/3979414
http://c0x.coding-guidelines.com/6.5.7.html
(1 << j) - 1 is a number with j one bits on the right
j bits
┌──────┐
00...0011...111
max is a number with all one bits
11...1111...111
Each one bit from max will become 0 when subtracting from the one bit from (1 << j) - 1, and remain 1 otherwise. Hence max - ((1 << j) - 1) will produce a value with j zero bits on the right
j...210 ← bit position
11...1111...11
- 00...0011...11
──────────────────
11...1100...00
That means the result is the bitwise not of (1 << j) - 1, i.e.
max - ((1 << j) - 1) == ~((1 << j) - 1)
Is (1<<(j-1)) equivalent to ((1 << j) - 1)?
1 << (j-1) shifts 1 j-1 places to the left and produces 2j - 1, so it has j-1 zeros on the right followed by a one 100...00. (1 << j) - 1 gives a number with j zeros on the right which is 2j - 1, as said above. Can you guess they're similar or not?