program for modular exponentiation

I am writing a code for (a^b)mod n
My code is working for small numbers but gives incorrect result for larger values (ex. (14^11)mod 21 should be 14 but it gives 12)
I am not getting where I have mistaken. Please help me out with this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  
#include<iostream>

using namespace std;
int main()
{
    int a,b,n,s,c,i,l;
    c=0;
    int arr[10];
    cout<<"enter the values of a";
    cin>>a;
    cout<<"b";
    cin>>b;
    cout<<"n"; 
    cin>>n;

               for(i=0;i<10;i++)
               {
                                while(b!=0){
                                arr[i]=b%2;
                                b=b/2;
                                c++;}
                                }
                                
               
    s=1;
    for(i=0;i<c;i++)
    {
                    if(arr[i]==1)
                    s=(s*(a^(2^i)))%n;
                   
                    }
   cout<<s<<endl;
   cin>>l;
    return 0;
    }
Last edited on
Topic archived. No new replies allowed.