博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
知道掩码求掩码长度_使用位掩码快速求幂
阅读量:2530 次
发布时间:2019-05-11

本文共 1779 字,大约阅读时间需要 5 分钟。

知道掩码求掩码长度

Problem statement: We have given two numbers "a" and "b". Now compute the value of "a" raise to the power "b" i.e. (a^b) by using bitmasks.

问题陈述:我们给了两个数字“ a”“ b” 。 现在, 通过使用位掩码计算将“ a”的值提高到幂“ b”,(a ^ b)

Example:

例:

Input:    a = 3 , b = 5    Output:    a^b = 243

Algorithm:

算法:

This method uses bitmasks and without using extra space to calculate a^b in O(log b) time.

此方法使用位掩码,并且不使用额外的空间来计算O(log b)时间中的a ^ b

  1. Let's take variable ans in which we store the result and initialize it with 1.

    让我们使用变量ans来存储结果,并使用1对其进行初始化。

  2. Extract last bit from b.

    从b中提取最后一位。

  3. If the Extracted bit is 1 multiply ans with a, otherwise if the Extracted bit is 0 then don't multiply.

    如果Extracted位为1 ,则将an与a相乘;否则,如果Extracted位为0,则不要相乘。

  4. Update a to a*a.

    更新 到*一个 。

  5. Discard rightmost bit i.e right shift b by 1.

    丢弃最右边的位,即右移b 1

  6. Repeat steps 2 to 5 until b becomes 0.

    重复步骤2到5,直到b变为0为止。

ans = 1    while(b>0)    {        if(b&1){            ans = (ans * a);        }        a = a*a;        b = b>>1;    }    //Now ans contains the value of a^b.

Explanation with example:

举例说明:

Fast Exponentiation using Bitmasking

C ++程序使用位掩码实现快速幂运算 (C++ program to implement Fast Exponentiation using Bitmasking)

#include
using namespace std;long long calculate(int a,int b){
// initialize ans with 1 long long ans = 1; while(b>0) {
// check if last bit 1 if(b&1){
ans = (ans * a); } // update value of a by a*a a = a*a; // right shift b by 1 b = b>>1; } return ans;}int main(){
int a,b; long long ans; cout<<"enter the value of a and b : "; cin>>a>>b; cout<<"a^b = "<
<
<

Output

输出量

First run:enter the value of a and b : 5 3a^b = 125Second run:enter the value of a and b : 37 7a^b = 94931877133Third run:enter the value of a and b : 37 0a^b = 1

翻译自:

知道掩码求掩码长度

转载地址:http://rsvzd.baihongyu.com/

你可能感兴趣的文章
[USACO18DEC]The Cow Gathering
查看>>
情感分析-英文电影评论
查看>>
王者荣耀游戏服务器架构的演进读后感
查看>>
关于ajax请求controller返回中文乱码的解决方法!
查看>>
Objective-C 和 Core Foundation 对象相互转换的内存管理总结
查看>>
IOS音频1:之采用四种方式播放音频文件(一)AudioToolbox AVFoundation OpenAL AUDIO QUEUE...
查看>>
Linux nmon 命令
查看>>
使用 urllib 构造请求对象
查看>>
sql server book
查看>>
长亭技术专栏 安全攻防技术分享
查看>>
sql server dba
查看>>
visualvm
查看>>
docker(4):coreos+docker+rancher真厉害
查看>>
设计模式之代理模式,学习笔记
查看>>
在Qsys中创建用户自定义IP
查看>>
【leetcode】Container With Most Water
查看>>
Python -- machine learning, neural network -- PyBrain 机器学习 神经网络
查看>>
一道dp题目
查看>>
mysql中间件研究(tddl atlas cobar sharding-jdbc)
查看>>
Cast-128 加密算法和 MyPassWord 的破解
查看>>