洛谷 P1010 [NOIP1998 普及组] 幂次方 刷题笔记

先用快速幂分解出 137=2^7+2^3+2^0。7 3 0 三个数

将 1315分解成 1315=2^10+2^8+2^5+2^1+2^0;

即分解成 10 8 5 1 0五个数 存入数组 

快速幂分解部分洛谷 P1226 【模板】快速幂 刷题笔记-CSDN博客

因为数据范围较小 2*10^4 小于2^15=32768; 直接对2的0次到15次用字符串写好

输出相应字符串即可

洛谷 P1010 [NOIP1998 普及组] 幂次方 刷题笔记_第1张图片

#include
using namespace std;
typedef long long ll;
int b[15];
int i=0;
// 2^15=32768>2*10^4;
ll quick_pow(int n){
    ll res=1;
    ll a=0;
    while(n){
        if(n&1){
            res*=a;
            b[i++]=a;
        }
        a++;
        n>>=1;
    }
    return res;

int main(){
    int x;
    cin>>x;
    quick_pow(x);
    
    string c[20]={"2(0)","2","2(2)","2(2+2(0))","2(2(2))","2(2(2)+2(0))","2(2(2)+2)","2(2(2)+2+2(0))",
    "2(2(2+2(0)))","2(2(2+2(0))+2(0))","2(2(2+2(0))+2)","2(2(2+2(0))+2+2(0)))",
    "2(2(2+2(0))+2(2(2)))","2(2(2+2(0))+2(2(2)))","2(2(2+2(0))+2(2)+2)","2(2(2+2(0))+2(2)+2+2(0))"};
    for(int j=i-1;j>=0;j--){
        cout<         //cout<         if(j!=0){
            cout<<"+";
        }
    }
    
    return 0;
}

解法2 

该思路来自大佬



 Mr_Wu 的个人中心 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

快速幂+递归 

使用log 2(x)函数每次求出数值上最接近n的2的k次 

递归分解k,直到分解成1或者0 ,输出相应的字符

n减去2的k次 (2的k次用快速幂处理)接着处理余数 。

 

#include
#include
using namespace std;
typedef long long ll;
ll quick_pow(int a,int b)
{
    ll res=1;
    while(b){
        if(b&1){
            res*=a;
        }
        a*=a;
        b>>=1;
    }
    return res;
}
void divide (int x){

    //求出 仅小于x 的2的k次方
    bool flag =false;
    while(x!=0){
            int temp=int(log2(x));
        if(flag){
            cout<<"+";
        }
            if(temp==1){
                cout<<"2";
            }else if(temp==0){
                cout<<"2(0)";
            }else{
                cout<<"2(";
                divide(temp);
                cout<<")";
            }
        x-=quick_pow(2,temp);
        flag =true;
    
    }
    
    
}

int main(){
    int n;
    cin >> n;
    divide(n);
    return 0;
    
    
}

你可能感兴趣的:(笔记)