32位数字乘积算法实现(不能使用64位整形)

来源:互联网 发布:phoneshop软件 编辑:程序博客网 时间:2024/05/18 01:27

32位数字乘积算法实现(不能使用64位整形),返回要求数的高32位和低32位。。

北京一行,确实见了不少东西,发现了自身的不少问题,例如算法方面、面向对象思想方面、C++语法方面。。等等,不一而足,当然整体上感觉自己还不错,体现很多细节理解上,下面是我最郁闷的一道题,在苏州浩辰软件(做autoCad的那家)面试的时候做的一道机试,最后没有弄出来,郁闷非常,(在那几乎面了一天,上午八点出发,下午7点才回到家,笔试,面试,面试,开发机试,算法机试,累个半死,其他都不错,就是这道题没搞定,当然最后也没有录取,可能不仅仅是这个原因,他们号称招了很多都是清华北大的,也许我真的跟他们有些我没有感觉到的明显差距吧。。哈哈 后话了)自己之前在算法上下的功夫确实太少,下面是今天没事时候实现的,测试通过,大致就是这些吧。。

C实现

+测试例子

void multiply(unsigned int first,unsigned int second,unsigned int& high,unsigned int& low)
{
    unsigned int h1 = first>>16;
    unsigned int l1 = first&((1<<16)-1);
    unsigned int h2 = second>>16;
    unsigned int l2 = second&((1<<16)-1);

    unsigned int a1h = (h1*l2)>>16;
    unsigned int a1l = (h1*l2)&((1<<16)-1);

    unsigned int a2h = (h2*l1)>>16;
    unsigned int a2l = (h2*l1)&((1<<16)-1);

    unsigned int lh = (l1*l2)>>16;
    unsigned int ll = (l1*l2)&((1<<16)-1);

    unsigned int ah =(a2l+a1l+lh)>>16;
    unsigned int al =(a2l+a1l+lh)&((1<<16)-1);

    high = h1*h2+a1h+a2h+ah;
    low = (al<<16)+ll;
}

#include <iostream>
using namespace std;
void main()
{
    unsigned int a = 1000000000;//(1<<32)-1;
    unsigned int b = (1<<32)-1;
    unsigned int c;
    unsigned int d;
    //long long c,d;
    multiply(a,b,c,d);
   
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;
    cout<<d<<endl;

    unsigned long long e=(unsigned long long)a*(unsigned long long)b;
    cout<<e<<endl;
    cout<<(e>>32)<<endl;
    cout<<(e&b)<<endl;
    getchar();
}

下午如果还是没事就用C#实现再整一下,看是否有什么不同。。。。

 

C#实现

+例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication8
{
    class Program
    {
        static uint a = 1;
        static void Main(string[] args)
        {
            uint e = 1000000000;
            uint b = (a << 31) - 1+(a<<31);
            uint c = new uint();
            uint d = new uint();
            multiply(e, b, ref c, ref d);
            Console.Write(e);
            Console.Write("  ");
            Console.Write(b);
            Console.Write("  ");
            Console.Write(c);
            Console.Write("  ");
            Console.Write(d);
            Console.ReadKey();
        }
        static void multiply(uint first,uint second,ref uint  high,ref uint low)
        {
           
            uint h1 = first>>16;
            uint l1 = first&((a<<16)-1);
            uint h2 = second>>16;
            uint l2 = second&((a<<16)-1);

            uint a1h = (h1*l2)>>16;
            uint a1l = (h1*l2)&((a<<16)-1);

            uint a2h = (h2*l1)>>16;
            uint a2l = (h2*l1)&((a<<16)-1);

            uint lh = (l1*l2)>>16;
            uint ll = (l1*l2)&((a<<16)-1);

            uint ah =(a2l+a1l+lh)>>16;
            uint al =(a2l+a1l+lh)&((1<<16)-1);

            high = h1*h2+a1h+a2h+ah;
            low = (al<<16)+ll;
        }
    }
}

原创粉丝点击