How will you implement pow(a,b) without using multiplication or division operators. You can use only add/substract operators.
Click for Solution

  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A int pow(int a,int b)
    {
    int temp=0,i;
    while(b!=0)
    {
    for(i=0;i<a;i++)
    temp=temp+a;
    a=temp;
    temp=0;
    b--;
    }
    return a;


  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A Using recursion, we can do it.

    #include

    /* assumption: b is greater than or equal to 0*/
    int pow(int a, int b)
    {
    if(b == 0)
    return 1;
    return multiply(a, pow(a, b-1));
    }

    /* assumption: y is greater than or equal to 0*/
    int multiply(int x, int y)
    {
    if(y == 0)
    return 0;
    return (x + multiply(x, y-1));
    }

    int main()
    {
    printf("\n %d", pow(5, 3));
    getchar();
    return 0;
    }



  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A void main()
    {
    int a,b,res,t;

    cout<<"enter a and b"<<endl;
    cin>>a>>b;

    res=a;

    for(int i=1;i<b;i++)
    {
    t=res;
    for(int j=1;j<a;j++)
    {
    res+=t;
    }
    }
    cout<<res;
    }


  • Warning: Illegal string offset 'name' in /home/prepdo6/gpl4you/discussquessub.php on line 681
    A I think in the given solution no of additions in the func. multiply for higher values of 'b' would be enormous.
    Therefore I propose a slightly different solution(90% same though).

    #include<stdio.h>
    #include<conio.h>

    int add(int x, int y)
    {
    if(x==1)
    return y;
    return (y + add(x-1,y));
    }

    int power(int a,int b)
    {
    if(b==0)
    return 1;
    if(b==1)
    return a;
    return add(a, power(a,b-1));
    }

    int main()
    {
    int a, b;

    printf("\nEnter the two numbers :\n");
    scanf("%d%d",&a,&b);

    printf("pow(a,b) = %d",power(a,b));

    getchar();
    return 0;

    }


[Insert Code]