A - 2^n - 2*n Editorial by en_translator
For beginners
- If you are new to learning programming and do not know where to start, please try Problem A "Welcome to AtCoder" from practice contest. There you can find a sample code for each language.
- Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in "AtCoder Beginners Selection".
- 「C++入門 AtCoder Programming Guide for beginners (APG4b)」 is a C++ tutorial for competitive programmers. Sadly, this is only in Japanese too.
- 「Python入門 AtCoder Programming Guide for beginners (APG4bPython)」 is a Python tutorial for competitive programmers. Again, this is only in Japanese.
Original proposer: admin
The problem can be answered by computing the \(N\)-th power of \(2\) and \(2 \times N\), and finding the difference between them.
The multiplication and subtraction seems relatively easy, but how can we compute the \(N\)-th power of \(2\)?
Solution \(1\): use a for loop
The \(N\)-th power of \(2\) can be computed using a for loop.
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int p=1;
for(int i=0;i<n;i++){
p=p*2;
}
cout << p-2*n << "\n";
return 0;
}
Solution \(2\): use the fast exponentiation algorithm
One may also adopt the fast exponentiation, which is an algorithm to find powers fast.
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int a=1,b=2,p=n;
while(p>0){
if(p%2==1){ a*=b; }
b*=b;
p/=2;
}
cout << a-2*n << "\n";
return 0;
}
Solution \(3\): use a standard function
For example, in Python one can compute powers using **.
Sample code (Python):
n = int(input())
print(2**n-2*n)
In C++ also, this problem can be solved with pow function, but note that the result of pow(int,int) against int-type values results in a double-type value, which requires an additional caution as it may lead to precision errors or output format violation.
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
cout << pow(2,n)-2*n << "\n";
return 0;
}
Solution \(4\): use the bitwise-shift operator
With bitwise-shift operator a<<k, one can obtain the value \(a \times 2^k\) (as long as an overflow does not occur).
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
cout << (1<<n)-2*n << "\n";
return 0;
}
posted:
last update: