0% found this document useful (0 votes)
23 views29 pages

Crypto Da

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

LAB ASSESMENT: - 01

PLAYFAIR METHOD
PYTHON
CODE: -
def toLowerCase(text):
return text.lower()

def removeSpaces(text):
newText = ""
for i in text:
if i == " ":
continue
else:
newText = newText + i
return newText

def Diagraph(text):
Diagraph = []
group = 0
for i in range(2, len(text), 2):
Diagraph.append(text[group:i])
group = i
Diagraph.append(text[group:])
return Diagraph

def FillerLetter(text):
k = len(text)
if k % 2 == 0:
for i in range(0, k, 2):
if text[i] == text[i+1]:
new_word = text[0:i+1] + 'x' + text[i+1:]
new_word = FillerLetter(new_word)
break
else:
new_word = text
else:
for i in range(0, k-1, 2):
if text[i] == text[i+1]:
LAB ASSESMENT: - 01
new_word = text[0:i+1] + 'x' + text[i+1:]
new_word = FillerLetter(new_word)
break
else:
new_word = text
return new_word

list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']

def generateKeyTable(word, list1):


key_letters = []
for i in word:
if i not in key_letters:
key_letters.append(i)

compElements = []
for i in key_letters:
if i not in compElements:
compElements.append(i)
for i in list1:
if i not in compElements:
compElements.append(i)

matrix = []
while compElements != []:
matrix.append(compElements[:5])
compElements = compElements[5:]

return matrix

def search(mat, element):


for i in range(5):
for j in range(5):
if(mat[i][j] == element):
return i, j
LAB ASSESMENT: - 01
def encrypt_RowRule(matr, e1r, e1c, e2r, e2c):
char1 = ''
if e1c == 4:
char1 = matr[e1r][0]
else:
char1 = matr[e1r][e1c+1]

char2 = ''
if e2c == 4:
char2 = matr[e2r][0]
else:
char2 = matr[e2r][e2c+1]

return char1, char2

def encrypt_ColumnRule(matr, e1r, e1c, e2r, e2c):


char1 = ''
if e1r == 4:
char1 = matr[0][e1c]
else:
char1 = matr[e1r+1][e1c]

char2 = ''
if e2r == 4:
char2 = matr[0][e2c]
else:
char2 = matr[e2r+1][e2c]

return char1, char2

def encrypt_RectangleRule(matr, e1r, e1c, e2r, e2c):


char1 = ''
char1 = matr[e1r][e2c]

char2 = ''
char2 = matr[e2r][e1c]
LAB ASSESMENT: - 01
return char1, char2

def encryptByPlayfairCipher(Matrix, plainList):


CipherText = []
for i in range(0, len(plainList)):
c1 = 0
c2 = 0
ele1_x, ele1_y = search(Matrix, plainList[i][0])
ele2_x, ele2_y = search(Matrix, plainList[i][1])
if ele1_x == ele2_x:
c1, c2 = encrypt_RowRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)
elif ele1_y == ele2_y:
c1, c2 = encrypt_ColumnRule(Matrix, ele1_x, ele1_y, ele2_x, ele2_y)
else:
c1, c2 = encrypt_RectangleRule(Matrix, ele1_x, ele1_y, ele2_x,
ele2_y)
cipher = c1 + c2
CipherText.append(cipher)
return CipherText

text_Plain = input("Enter the plain text: ")


text_Plain = removeSpaces(toLowerCase(text_Plain))
PlainTextList = Diagraph(FillerLetter(text_Plain))

if len(PlainTextList[-1]) != 2:
PlainTextList[-1] = PlainTextList[-1] + 'z'

key = input("Enter the key: ")


key = toLowerCase(key)

Matrix = generateKeyTable(key, list1)


print("Plain Text:", text_Plain)

CipherList = encryptByPlayfairCipher(Matrix, PlainTextList)

CipherText = ""
for i in CipherList:
LAB ASSESMENT: - 01
CipherText += i

print("CipherText:", CipherText)

JAVA: -
import java.util.*;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the plain text: ");


String plainText = scanner.nextLine();

System.out.print("Enter the keyword: ");


String keyword = scanner.nextLine();

String encryptedText = encryptText(plainText, keyword);


System.out.println("Encrypted Text: " + encryptedText);
}

public static String removeDuplicate(String s) {


int j, index = 0, len = s.length();
char c[] = s.toCharArray();

for (int i = 0; i < len; i++) {


for (j = 0; j < i; j++) {
if (c[i] == c[j])
break;
}
if (i == j)
c[index++] = c[i];
}

return new String(Arrays.copyOf(c, index));


}
LAB ASSESMENT: - 01
public static String removeWhiteSpace(char[] ch, String key) {
char[] c = key.toCharArray();

for (int i = 0; i < c.length; i++) {


for (int j = 0; j < ch.length; j++) {
if (c[i] == ch[j])
c[i] = ' ';
}
}

key = new String(c);


return key.replaceAll(" ", "");
}

public static String makePair(String plainText) {


StringBuilder sb = new StringBuilder();
char c = 'a';

for (int i = 0; i < plainText.length(); i++) {


if (plainText.charAt(i) == ' ')
continue;
else {
c = plainText.charAt(i);
sb.append(plainText.charAt(i));
}

if (i < plainText.length() - 1) {
if (plainText.charAt(i) == plainText.charAt(i + 1))
sb.append("x");
}
}

if (sb.length() % 2 != 0)
sb.append("x");

return sb.toString();
LAB ASSESMENT: - 01
}

public static int[] findIJ(char a, char b, char x[][]) {


int[] y = new int[4];

if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';

for (int i = 0; i < 5; i++) {


for (int j = 0; j < 5; j++) {
if (x[i][j] == a) {
y[0] = i;
y[1] = j;
} else if (x[i][j] == b) {
y[2] = i;
y[3] = j;
}
}
}

if (y[0] == y[2]) {
y[1] += 1;
y[3] += 1;
} else if (y[1] == y[3]) {
y[0] += 1;
y[2] += 1;
}

for (int i = 0; i < 4; i++)


y[i] %= 5;

return y;
}

public static String encryptText(String plainText, String keyword) {


LAB ASSESMENT: - 01
keyword = removeDuplicate(keyword);

char[] keyChars = keyword.toCharArray();


String alphabet = "abcdefghiklmnopqrstuvwxyz";
alphabet = removeWhiteSpace(keyChars, alphabet);

char[] alphabetChars = alphabet.toCharArray();


char[][] matrix = new char[5][5];

int alphabetIndex = 0, keyIndex = 0;

for (int i = 0; i < 5; i++) {


for (int j = 0; j < 5; j++) {
if (keyIndex < keyword.length())
matrix[i][j] = keyChars[keyIndex++];
else
matrix[i][j] = alphabetChars[alphabetIndex++];
}
}

String pairText = makePair(plainText);


StringBuilder encryptedText = new StringBuilder();

for (int i = 0; i < pairText.length(); i += 2) {


if (i < pairText.length() - 1) {
int[] indices = findIJ(pairText.charAt(i), pairText.charAt(i + 1),
matrix);

if (indices[0] == indices[2]) {
encryptedText.append(matrix[indices[0]][indices[1]]);
encryptedText.append(matrix[indices[0]][indices[3]]);
} else if (indices[1] == indices[3]) {
encryptedText.append(matrix[indices[0]][indices[1]]);
encryptedText.append(matrix[indices[2]][indices[1]]);
} else {
encryptedText.append(matrix[indices[0]][indices[3]]);
encryptedText.append(matrix[indices[2]][indices[1]]);
LAB ASSESMENT: - 01
}
}
}

return encryptedText.toString();
}
}

CEASER Cipher
Code:-
Python
# This function generates the
# key in a cyclic manner until
# it's length isn't equal to
# the length of original text
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return key
else:
for i in range(len(string) - len(key)):
key.append(key[i % len(key)])
return ''.join(key)

# This function returns the


# encrypted text generated
# with the help of the key
def cipherText(string, key):
cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) + ord(key[i])) % 26
x += ord('A')
cipher_text.append(chr(x))
return ''.join(cipher_text)
LAB ASSESMENT: - 01
# This function decrypts the
# encrypted text and returns
# the original text
def originalText(cipher_text, key):
orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) - ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
return ''.join(orig_text)

# Driver code
if __name__ == "__main__":
string = input("Enter the string: ").upper()
keyword = input("Enter the keyword: ").upper()
key = generateKey(string, keyword)
cipher_text = cipherText(string, key)
print("Ciphertext:", cipher_text)
print("Original/Decrypted Text:", originalText(cipher_text, key))

JAVA:-
// Java code to implement Vigenere Cipher

class Main
{

// This function generates the key in


// a cyclic manner until it's length isi'nt
// equal to the length of original text
static String generateKey(String str, String key)
{
int x = str.length();

for (int i = 0; ; i++)


{
if (x == i)
i = 0;
LAB ASSESMENT: - 01
if (key.length() == str.length())
break;
key+=(key.charAt(i));
}
return key;
}

// This function returns the encrypted text


// generated with the help of the key
static String cipherText(String str, String key)
{
String cipher_text="";

for (int i = 0; i < str.length(); i++)


{
// converting in range 0-25
int x = (str.charAt(i) + key.charAt(i)) %26;

// convert into alphabets(ASCII)


x += 'A';

cipher_text+=(char)(x);
}
return cipher_text;
}

// This function decrypts the encrypted text


// and returns the original text
static String originalText(String cipher_text, String key)
{
String orig_text="";

for (int i = 0 ; i < cipher_text.length() &&


i < key.length(); i++)
{
// converting in range 0-25
int x = (cipher_text.charAt(i) -
LAB ASSESMENT: - 01
key.charAt(i) + 26) %26;

// convert into alphabets(ASCII)


x += 'A';
orig_text+=(char)(x);
}
return orig_text;
}

// This function will convert the lower case character to Upper case
static String LowerToUpper(String s)
{
StringBuffer str =new StringBuffer(s);
for(int i = 0; i < s.length(); i++)
{
if(Character.isLowerCase(s.charAt(i)))
{
str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
}
s = str.toString();
return s;
}

// Driver code
public static void main(String[] args)
{
String Str = "VELLOREINSTITUTE";
String Keyword = "SCOPE";

String str = LowerToUpper(Str);


String keyword = LowerToUpper(Keyword);

String key = generateKey(str, keyword);


String cipher_text = cipherText(str, key);

System.out.println("Ciphertext : "
LAB ASSESMENT: - 01
+ cipher_text + "\n");

System.out.println("Original/Decrypted Text : "


+ originalText(cipher_text, key));
}
}

HILL CYPHER
CODE : -
import java.util.Scanner;

public class Main {


public static int[][] keymat = new int[][]{{1, 2, 1}, {2, 3, 2}, {2, 2, 1}};
public static int[][] invkeymat = new int[][]{{-1, 0, 1}, {2, -1, 0}, {-2, 2, -
1}};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
String text = sc.nextLine();
text = text.toUpperCase();
text = text.replaceAll("\\s", "");
int n = text.length() % 3;
if (n != 0) {
for (int i = 1; i <= (3 - n); i++) {
text += 'X';
}
}
System.out.println("Padded Text: " + text);
String outtext = encryptText(text);
System.out.println("Encrypted Message: " + outtext);
String outtext1 = decryptText(outtext);
System.out.println("Decrypted Message: " + outtext1);
}
LAB ASSESMENT: - 01
private static String encryptText(String text) {
StringBuilder outtext = new StringBuilder();
for (int i = 0; i < text.length(); i += 3) {
outtext.append(encrypt(text.charAt(i), text.charAt(i + 1), text.charAt(i
+ 2)));
}
return outtext.toString();
}

private static String decryptText(String text) {


StringBuilder outtext = new StringBuilder();
for (int i = 0; i < text.length(); i += 3) {
outtext.append(decrypt(text.charAt(i), text.charAt(i + 1), text.charAt(i
+ 2)));
}
return outtext.toString();
}

private static String encrypt(char a, char b, char c) {

StringBuilder ret = new StringBuilder();


int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
a = key.charAt(mod(x, 26));
b = key.charAt(mod(y, 26));
c = key.charAt(mod(z, 26));
ret.append(a).append(b).append(c);
return ret.toString();
}

private static String decrypt(char a, char b, char c) {


LAB ASSESMENT: - 01
StringBuilder ret = new StringBuilder();
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * invkeymat[0][0] + posb * invkeymat[1][0] + posc *
invkeymat[2][0];
y = posa * invkeymat[0][1] + posb * invkeymat[1][1] + posc *
invkeymat[2][1];
z = posa * invkeymat[0][2] + posb * invkeymat[1][2] + posc *
invkeymat[2][2];
a = key.charAt(mod(x, 26));
b = key.charAt(mod(y, 26));
c = key.charAt(mod(z, 26));
ret.append(a).append(b).append(c);
return ret.toString();
}

private static int mod(int x, int m) {


return (x % m + m)%m;
}
}

EXTENDED FERMAT THEOREM


// Java program to find modular
// inverse of a under modulo m
// using Fermat's little theorem.
// This program works only if m is prime.

class Main {
static int __gcd(int a, int b)
{

if (b == 0) {
LAB ASSESMENT: - 01
return a;
}
else {
return __gcd(b, a % b);
}
}

// To compute x^y under modulo m


static int power(int x, int y, int m)
{
if (y == 0)
return 1;
int p = power(x, y / 2, m) % m;
p = (p * p) % m;

return (y % 2 == 0) ? p : (x * p) % m;
}

// Function to find modular


// inverse of a under modulo m
// Assumption: m is prime
static void modInverse(int a, int m)
{
if (__gcd(a, m) != 1)
System.out.print("Inverse doesn't exist");

else {

// If a and m are relatively prime, then


// modulo inverse is a^(m-2) mode m
System.out.print(
"Modular multiplicative inverse is "
+ power(a, m - 2, m));
}
}

// Driver code
LAB ASSESMENT: - 01
public static void main(String[] args)
{
int a = 3, m = 11;
modInverse(a, m);
}
}

Extended eucledian therorem :


import java.util.Scanner;

public class Main {

// Function to find the greatest common divisor (GCD) of two numbers


public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

// Extended Euclidean Algorithm


public static int[] extendedEuclidean(int a, int b) {
int[] result = new int[3];
if (b == 0) {
result[0] = a;
result[1] = 1;
result[2] = 0;
return result;
}
int[] temp = extendedEuclidean(b, a % b);
result[0] = temp[0];
result[1] = temp[2];
result[2] = temp[1] - (a / b) * temp[2];
return result;
}
LAB ASSESMENT: - 01
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number (a): ");


int a = scanner.nextInt();

System.out.print("Enter the second number (b): ");


int b = scanner.nextInt();

// Calculate the gcd of a and b


int gcd = gcd(a, b);
System.out.println("GCD of " + a + " and " + b + " is: " + gcd);

// Calculate the coefficients x and y such that ax + by = gcd(a, b)


int[] coefficients = extendedEuclidean(a, b);
int s = coefficients[1]; // Coefficient x
int t = coefficients[2]; // Coefficient y
System.out.println("Extended Euclidean Algorithm:");
System.out.println("Coefficients s and t such that as + bt = gcd(a, b):");
System.out.println("s = " + s + ", t = " + t);

scanner.close();
}
}

MULTIPLICATIVE INVERSE
USING EXTENDE EUCLEADIAN
THEOREM
import java.util.Scanner;

public class Main {

// Function to find the greatest common divisor (GCD) of two numbers


public static int gcd(int a, int b) {
LAB ASSESMENT: - 01
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

// Extended Euclidean Algorithm to find the multiplicative inverse


public static int multiplicativeInverse(int a, int m) {
// Check if a and m are coprime (i.e., gcd(a, m) == 1)
if (gcd(a, m) != 1) {
System.out.println("Multiplicative inverse does not exist");
return -1;
}

// Extended Euclidean Algorithm


int m0 = m;
int y = 0, x = 1;

while (a > 1) {
// q is quotient
int q = a / m;
int t = m;

// m is remainder now; process same as Euclid's algorithm


m = a % m;
a = t;
t = y;

// Update y and x
y = x - q * y;
x = t;
}

// Make x positive
if (x < 0) {
x += m0;
}
LAB ASSESMENT: - 01
return x;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number for which you want to find the


multiplicative inverse: ");
int a = scanner.nextInt();

System.out.print("Enter the modulus: ");


int m = scanner.nextInt();

// Find the multiplicative inverse of a modulo m


int inverse = multiplicativeInverse(a, m);

if (inverse != -1) {
System.out.println("Multiplicative inverse of " + a + " modulo " + m
+ " is: " + inverse);
}

scanner.close();
}
}

Inverse via Euler's


Theorem
import java.util.Scanner;

public class Main {


// Function to calculate GCD of two numbers
static int gcd(int a, int b) {
LAB ASSESMENT: - 01
if (b == 0)
return a;
return gcd(b, a % b);
}

// Function to calculate power a^b mod m


static int power(int a, int b, int m) {
int res = 1;
a %= m;
while (b > 0) {
if ((b & 1) == 1)
res = (res * a) % m;
b >>= 1;
a = (a * a) % m;
}
return res;
}

// Function to calculate modular inverse using Euler's theorem


static int modInverse(int a, int b, int m) {
int g = gcd(a, m);
if (g != 1) {
System.out.println("Inverse doesn't exist");
return -1;
} else {
// φ(m) = m - 1 for prime modulus m
return power(a, m - 2, m);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base (a): ");
int a = scanner.nextInt();
System.out.print("Enter the exponent (-b): ");
int b = scanner.nextInt();
System.out.print("Enter the modulus (n): ");
LAB ASSESMENT: - 01
int n = scanner.nextInt();

int inverse = modInverse(a, b, n);


if (inverse != -1)
System.out.println("The modular inverse of " + a + "^(-" + b + ") mod
" + n + " is: " + inverse);
scanner.close();
}
}

Inverse via Fermat therorem


import java.util.Scanner;

public class Main {

// Function to calculate power a^b mod m


static long power(long a, long b, long m) {
if (b == 0)
return 1;
long result = power(a, b / 2, m) % m;
result = (result * result) % m;
if (b % 2 == 1)
result = (result * a) % m;
return result;
}

// Function to calculate modular inverse using Fermat's theorem


static long modInverse(long a, long n) {
// If n is prime, then a^(n-2) ≡ a^(-1) (mod n)
return power(a, n - 2, n);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of a: ");
long a = scanner.nextLong();
LAB ASSESMENT: - 01
System.out.print("Enter the value of b: ");
long b = scanner.nextLong();
System.out.print("Enter the value of n: ");
long n = scanner.nextLong();

long inverse = modInverse(a, n);


long result = power(inverse, b, n);

System.out.println(a + "^(-" + b + ") mod " + n + " = " + result);

scanner.close();
}
}

TO FIND MODULUS USING


FERMAT AND EULERS THOREM
import java.util.Scanner;

public class Main {

// Function to calculate power a^b mod m using Fermat's theorem


static long powerFermat(long a, long b, long m) {
if (b == 0)
return 1;
long result = powerFermat(a, b / 2, m) % m;
result = (result * result) % m;
if (b % 2 == 1)
result = (result * a) % m;
return result;
}

// Function to calculate power a^b mod m using Euler's theorem


static long powerEuler(long a, long b, long m) {
long result = 1;
a = a % m;
LAB ASSESMENT: - 01
while (b > 0) {
if (b % 2 == 1)
result = (result * a) % m;
b = b >> 1;
a = (a * a) % m;
}
return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of a: ");


long a = scanner.nextLong();
System.out.print("Enter the value of b: ");
long b = scanner.nextLong();
System.out.print("Enter the value of n: ");
long n = scanner.nextLong();

// Using Fermat's theorem


long resultFermat = powerFermat(a, b, n);
System.out.println("Using Fermat's theorem: " + a + "^" + b + " mod " +
n + " = " + resultFermat);

// Using Euler's theorem


long resultEuler = powerEuler(a, b, n);
System.out.println("Using Euler's theorem: " + a + "^" + b + " mod " + n
+ " = " + resultEuler);

scanner.close();
}
}

CHINESE REMAINDER THEOREM


import java.util.Scanner;
LAB ASSESMENT: - 01
public class Main {

// Function to find the modular inverse of 'a' under modulo 'm'


static long modInverse(long a, long m) {
long m0 = m, t, q;
long x0 = 0, x1 = 1;

if (m == 1)
return 0;

// Apply extended Euclid Algorithm


while (a > 1) {
q = a / m;
t = m;
m = a % m;
a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}

// Make x1 positive
if (x1 < 0)
x1 += m0;

return x1;
}

// Function to find the Chinese Remainder Theorem


static long findCRT(long[] num, long[] rem, int k) {
// Compute product of all numbers
long prod = 1;
for (int i = 0; i < k; i++)
prod *= num[i];

// Initialize result
long result = 0;
LAB ASSESMENT: - 01
// Apply Chinese Remainder Theorem
for (int i = 0; i < k; i++) {
long pp = prod / num[i];
result += rem[i] * modInverse(pp, num[i]) * pp;
}

return result % prod;


}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of equations: ");


int k = scanner.nextInt();

long[] num = new long[k];


long[] rem = new long[k];

for (int i = 0; i < k; i++) {


System.out.print("Enter value of num[" + i + "]: ");
num[i] = scanner.nextLong();
System.out.print("Enter value of rem[" + i + "]: ");
rem[i] = scanner.nextLong();
}

long result = findCRT(num, rem, k);


System.out.println("The solution using Chinese Remainder Theorem is:
" + result);

scanner.close();
}
}

FAST EXPONENT MODULUS


import java.util.Scanner;
LAB ASSESMENT: - 01
public class Main {

// Function to calculate (base^exponent) % modulus


static long power(long base, long exponent, long modulus) {
long result = 1;
base = base % modulus;

while (exponent > 0) {


// If exponent is odd, multiply base with result
if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
// Exponent must be even now, divide it by 2
exponent = exponent >> 1;
// Multiply base with itself
base = (base * base) % modulus;
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of a: ");


long a = scanner.nextLong();
System.out.print("Enter the value of b: ");
long b = scanner.nextLong();
System.out.print("Enter the value of n: ");
long n = scanner.nextLong();

long result = power(a, b, n);


System.out.println("Result of (" + a + "^" + b + ") % " + n + " = " +
result);

scanner.close();
LAB ASSESMENT: - 01
}
}

FIND USING SQUARE AND


MLTIPLY METHOD
import java.util.Scanner;

public class SquareAndMultiply {

// Function to calculate (base^exponent) % modulus using square and


multiply method
static long power(long base, long exponent, long modulus) {
long result = 1;
base = base % modulus;

while (exponent > 0) {


if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
base = (base * base) % modulus;
exponent /= 2;
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the value of a: ");


long a = scanner.nextLong();
System.out.print("Enter the value of b: ");
long b = scanner.nextLong();
System.out.print("Enter the value of n: ");
long n = scanner.nextLong();
LAB ASSESMENT: - 01
long result = power(a, b, n);
System.out.println("Result of (" + a + "^" + b + ") % " + n + " = " +
result);

scanner.close();
}
}

You might also like