Kn0wthyself's blog

By Kn0wthyself, 6 weeks ago, In English

248913591 Here I use directly pow function in cout; so it gives a value which is in power. But when I store the it one integer varible than it gives direct value. so in contest time or problem solving time if we use directly pow function in cout it will gives error. have anyone opinion about this to ignore this problem using pow function directly in cout .

Wrong Solution

#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        long long n;
        cin>>n;
        int a=log2(n);
        int ans=pow(2,a);
        cout<<ans<<endl;
    }
    return 0;
}

Right solution

~~~~~ ~~~~~ #include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ long long n; cin>>n; int a=log2(n); int ans=pow(2,a); cout<<ans<<endl; } return 0; } ~~~~~ ~~~~~

Tags pow
  • Vote: I like it
  • -2
  • Vote: I do not like it

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Kn0wthyself (previous revision, new revision, compare).

»
6 weeks ago, # |
  Vote: I like it +2 Vote: I do not like it

Do not use built in pow function provided by cpp as it does not provide accurate answer for larger powers plus it can cause overflow errors if you want your answer taken modulo with some M (usually 1e9+7), instead use binary exponentiation which provides accurate answer in O(log n) time and it also gives you answer taken modulo with some integer.

You can reffer to this page if you do not know about binary exponentiation.

»
6 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Use Binary Exponentiation instead. Can refer to the Binary exponentiation code below:

long long binpow(long long a, long long b)

{

if (b == 0)
    return 1;

long long res = binpow(a, b / 2);

if (b % 2)
    return res * res * a;

else
    return res * res;

}

»
6 weeks ago, # |
  Vote: I like it +13 Vote: I do not like it

1) What data type returned by the pow function do you see here?

2) Do you know how floating point values are printed by cout?