-
Notifications
You must be signed in to change notification settings - Fork 1k
/
bigmod_algorithm.c
73 lines (61 loc) · 1.89 KB
/
bigmod_algorithm.c
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Given a number's base and power.
return the number.
base and power can be large as 10^6 to 10^9
so we need to mod with some big number in order to get the number
this can be done by bigmod algorithm
*/
#include <stdio.h>
#include <math.h>
// this get_new_number_by_bigmod will give us the new number
long long int get_new_number_by_bigmod(long long int base, long long int power, long long int mod_number)
{
long long int new_number;
if(power == 0)
{
// no matter what base is , as power is 0 answer 1
return 1;
}
else if(power % 2 == 0)
{
/* as power is even,
we will divide the power each step by 2
9^18 will be 9^9 , 9^9
and thus goes on by recursive call
*/
new_number = get_new_number_by_bigmod(base , power / 2, mod_number);
return ((new_number * new_number) % mod_number);
}
else
{
/* as power is odd,
we will take power - 1
9^15 = 9^14 , 9^1
and thus goes on by recursive call
*/
long long int temp = get_new_number_by_bigmod(base , power - 1 , mod_number);
return ((( base % mod_number)* temp)% mod_number);
}
}
int main()
{
printf("Enter the base number and power number : ");
long long int base , power;
scanf("%lld %lld", &base, &power);
printf("Enter the mod number: ");
long long int mod_number;
scanf("%lld", &mod_number);
long long int new_number = get_new_number_by_bigmod(base, power, mod_number);
printf("After applying Bigmod algorithm the new number is : \n");
printf("%lld \n", new_number);
}
/*
Standard Input and Output
Enter the base number and power number :
45 67
Enter the mod number: 1000456
After applying Bigmod algorithm the new number is :
595941
Time Complexity : O( log N )
Space Complexity : O( 1 )
*/