Friday, July 31, 2020

Write a Program to demonstrate use of Username and Password (login id and password) in C.

Username and Password (login id and  password) in C.


#include<stdio.h>
int main()
{
 int i;
 char char1, username[10], password[10];

  printf("Enter your Username ::");
 gets(username);
 
 printf("Enter your Password ::");
 gets(password);
 
 if(strcmp(username,"student123")==0 && strcmp(password,"admin@123")==0)
  printf("\n Welcome....\n Login Successfully");
 else
  printf("Invalid Username/Password.");
 return 0;
}


OUTPUT

Enter your Username ::student123
Enter your Password ::admin@123

 Welcome....
 Login Successfully

Implement the DES algorithm in C++.

 DES algorithm in C++.

#include <iostream>
#include <string>
using namespace std;

// Array to hold the 16 keys

string round_keys[16];
string shift_left_once(string key_chunk){ 
    string shifted="";  
        for(int i = 1; i < 28; i++){ 
            shifted += key_chunk[i]; 
        } 
        shifted += key_chunk[0];   
    return shifted; 
string shift_left_twice(string key_chunk){ 
    string shifted=""; 
    for(int i = 0; i < 2; i++){ 
        for(int j = 1; j < 28; j++){ 
            shifted += key_chunk[j]; 
        } 
        shifted += key_chunk[0]; 
        key_chunk= shifted; 
        shifted =""; 
    } 
    return key_chunk; 
}
void generate_keys(string key){
// The PC1 table 
int pc1[56] = {
57,49,41,33,25,17,9, 
1,58,50,42,34,26,18, 
10,2,59,51,43,35,27, 
19,11,3,60,52,44,36,  
63,55,47,39,31,23,15, 
7,62,54,46,38,30,22, 
14,6,61,53,45,37,29, 
21,13,5,28,20,12,4 
};
// The PC2 table
int pc2[48] = { 
14,17,11,24,1,5, 
3,28,15,6,21,10, 
23,19,12,4,26,8, 
16,7,27,20,13,2, 
41,52,31,37,47,55, 
30,40,51,45,33,48, 
44,49,39,56,34,53, 
46,42,50,36,29,32 
}; 

string perm_key =""; 
for(int i = 0; i < 56; i++){ 
perm_key+= key[pc1[i]-1]; 

string left= perm_key.substr(0, 28); 
string right= perm_key.substr(28, 28); 
// Generating 16 keys
for(int i=0; i<16; i++){ 

if(i == 0 || i == 1 || i==8 || i==15 ){
left= shift_left_once(left); 
right= shift_left_once(right);

else{
left= shift_left_twice(left); 
right= shift_left_twice(right);
}

string combined_key = left + right;
string round_key = ""; 

for(int i = 0; i < 48; i++){ 
round_key += combined_key[pc2[i]-1]; 
}   
round_keys[i] = round_key;
cout<<"Key "<<i+1<<": "<<round_keys[i]<<endl; 

}
int main(){  
string key = "10101010101110110000100100011000001001110011";
  generate_keys(key);


OUTPUT

Key 1: 0000!010011001�100000110001011110010
Key 2: 0100101100000�!00000011011110110010
Key 3: 0000�10101101010010010100111010110101
Key 4: 1110�00010!0000011010110110110001
Key 5: 010�00110!011000101001111010011000101
Key 6: 11000000010!001�101001101001010110
Key 7: !11000100101010100011010111001100000
Key 8: 00010!111�000000101100000110010110
Key 9: !000100101101000100100110110011010
Key 10: 00000101101!00010�1000101010010111
Key 11: 010110100!0011100010101011111000101
Key 12: 1001011000001!�0100101101000001111011
Key 13: �001101!0001100000110101111000010011
Key 14: 0010000110�!100011100011000111000
Key 15: 001001001�00010010!1110101001010110
Key 16: 001!00000011001011100111100010010111

Write a Program Key generation in Simplified DES in C.

Key generation in Simplified DES in C.


#include<stdio.h>
int main()
{
 int i, count=0, p8[8]={6,7,8,9,1,2,3,4};
 int p10[10]={6,7,8,9,10,1,2,3,4,5};
 
 char input[11], k1[10], k2[10], temp[11];
 char LS1[5], LS2[5];
 printf("Enter 10 Bits Input ::");
 scanf("%s",input); 
 input[10]='\0';

 for(i=0; i<10; i++)
 {
  count = p10[i];
  temp[i] = input[count-1];
 }
 temp[i]='\0';
 printf("\nYour p10 key is ::");
 for(i=0; i<10; i++)
 { printf("%d,",p10[i]); }
 
 printf("\nBits After p10 ::");
 puts(temp);
 for(i=0; i<5; i++)
 {
  if(i==4)
   temp[i]=temp[0];
  else
   temp[i]=temp[i+1];   
 }

 for(i=5; i<10; i++)
 {
  if(i==9)
   temp[i]=temp[5];
  else
   temp[i]=temp[i+1];   
 }
 printf("Output After LS-1 ::");
 puts(temp);
 
 printf("\nYour p8 Key is  ::");
 for(i=0; i<8; i++)
 { printf("%d,",p8[i]); }


 for(i=0; i<8; i++)
 {
  count = p8[i];
  k1[i] = temp[count-1];
 }
 printf("\nYour key k1 is :");
 puts(k1); 
}

OUTPUT

Enter 10 Bits Input :: Computer

Your p10 key is :: 6,7,8,9,10,1,2,3,4,5,

Bits After p10 :: ter
Output After LS-1 :: er

Your p8 Key is  :: 6,7,8,9,1,2,3,4,
Your key k1 is : ompuer

Implement DES Algorithm in Python.

DES Algorithm in Python.


#Initial permut matrix 
PI = [58, 50, 42, 34, 26, 18, 10, 2,
      60, 52, 44, 36, 28, 20, 12, 4,
      62, 54, 46, 38, 30, 22, 14, 6,
      64, 56, 48, 40, 32, 24, 16, 8,
      57, 49, 41, 33, 25, 17, 9, 1,
      59, 51, 43, 35, 27, 19, 11, 3,
      61, 53, 45, 37, 29, 21, 13, 5,
      63, 55, 47, 39, 31, 23, 15, 7]

#Initial permut made on the key
CP_1 = [57, 49, 41, 33, 25, 17, 9,
        1, 58, 50, 42, 34, 26, 18,
        10, 2, 59, 51, 43, 35, 27,
        19, 11, 3, 60, 52, 44, 36,
        63, 55, 47, 39, 31, 23, 15,
        7, 62, 54, 46, 38, 30, 22,
        14, 6, 61, 53, 45, 37, 29,
        21, 13, 5, 28, 20, 12, 4]

#Permut applied on shifted key to get Ki+1
CP_2 = [14, 17, 11, 24, 1, 5, 3, 28,
        15, 6, 21, 10, 23, 19, 12, 4,
        26, 8, 16, 7, 27, 20, 13, 2,
        41, 52, 31, 37, 47, 55, 30, 40,
        51, 45, 33, 48, 44, 49, 39, 56,
        34, 53, 46, 42, 50, 36, 29, 32]

#Expand matrix to get a 48-bits matrix of datas to apply the x-or with Ki
E = [32, 1, 2, 3, 4, 5,
     4, 5, 6, 7, 8, 9,
     8, 9, 10, 11, 12, 13,
     12, 13, 14, 15, 16, 17,
     16, 17, 18, 19, 20, 21,
     20, 21, 22, 23, 24, 25,
     24, 25, 26, 27, 28, 29,
     28, 29, 30, 31, 32, 1]

#Here Define SBOX
S_BOX = [
         
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
 [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
 [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
 [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
],

[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
 [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
 [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
 [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
],

[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
 [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
 [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
 [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
],

[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
 [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
 [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
 [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
],  

[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
 [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
 [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
 [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
], 

[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
 [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
 [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
 [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
], 

[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
 [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
 [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
 [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
],
   
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
 [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
 [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
 [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
]
#Permut made after each SBox substitution for each round
P = [16, 7, 20, 21, 29, 12, 28, 17,
     1, 15, 23, 26, 5, 18, 31, 10,
     2, 8, 24, 14, 32, 27, 3, 9,
     19, 13, 30, 6, 22, 11, 4, 25]
#Final permut for datas after the 16 rounds
PI_1 = [40, 8, 48, 16, 56, 24, 64, 32,
        39, 7, 47, 15, 55, 23, 63, 31,
        38, 6, 46, 14, 54, 22, 62, 30,
        37, 5, 45, 13, 53, 21, 61, 29,
        36, 4, 44, 12, 52, 20, 60, 28,
        35, 3, 43, 11, 51, 19, 59, 27,
        34, 2, 42, 10, 50, 18, 58, 26,
        33, 1, 41, 9, 49, 17, 57, 25]
#Matrix that determine the shift for each round of keys
SHIFT = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]
def string_to_bit_array(text):#Convert a string into a list of bits
    array = list()
    for char in text:
        binval = binvalue(char, 8)#Get the char value on one byte
        array.extend([int(x) for x in list(binval)]) #Add the bits to the final list
    return array
def bit_array_to_string(array): #Recreate the string from the bit array
    res = ''.join([chr(int(y,2)) for y in [''.join([str(x) for x in _bytes]) for _bytes in  nsplit(array,8)]])   
    return res
def binvalue(val, bitsize): #Return the binary value as a string of the given size 
    binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]
    if len(binval) > bitsize:
        raise "binary value larger than the expected size"
    while len(binval) < bitsize:
        binval = "0"+binval #Add as many 0 as needed to get the wanted size
    return binval

def nsplit(s, n):#Split a list into sublists of size "n"
    return [s[k:k+n] for k in range(0, len(s), n)]
ENCRYPT=1
DECRYPT=0
class des():
    def __init__(self):
        self.password = None
        self.text = None
        self.keys = list()     
    def run(self, key, text, action=ENCRYPT, padding=False):
        if len(key) < 8:
            raise "Key Should be 8 bytes long"
            #If key size is above 8-bytes, cut to be 8-bytes long 
        elif len(key) > 8:
            key = key[:8]   
        self.password = key
        self.text = text       
        if padding and action==ENCRYPT:
            self.addPadding()
            #If not padding specified data size must be multiple of 8 bytes
        elif len(self.text) % 8 != 0:
            raise "Data size should be multiple of 8"     
            #Generate all the keys   
        self.generatekeys() 
        #Split the text in blocks of 8 bytes so 64 bits
        text_blocks = nsplit(self.text, 8) 
        result = list()
        #Loop over all the blocks of data
        for block in text_blocks:
            block = string_to_bit_array(block)#Convert the block in bit array
            block = self.permut(block,PI)#Apply the initial permutation
            g, d = nsplit(block, 32) #g(LEFT), d(RIGHT)
            tmp = None
            for i in range(16): #Do the 16 rounds
                d_e = self.expand(d, E) #Expand d to match Ki size (48bits)
                if action == ENCRYPT:
                    tmp = self.xor(self.keys[i], d_e)#If encrypt use Ki
                else:
                    tmp = self.xor(self.keys[15-i], d_e)#If decrypt start by the last key
                tmp = self.substitute(tmp) #Method that will apply the SBOXes
                tmp = self.permut(tmp, P)
                tmp = self.xor(g, tmp)
                g = d
                d = tmp
            result += self.permut(d+g, PI_1) #Do the last permut and append the result to result
        final_res = bit_array_to_string(result)
        if padding and action==DECRYPT:
            return self.removePadding(final_res) #Remove the padding if decrypt and padding is true
        else:
            return final_res #Return the final string of data ciphered/deciphered
    
    def substitute(self, d_e):#Substitute bytes using SBOX
        subblocks = nsplit(d_e, 6)#Split bit array into sublist of 6 bits
        result = list()
        for i in range(len(subblocks)): #For all the sublists
            block = subblocks[i]
            row = int(str(block[0])+str(block[5]),2)#Get the row with the first and last bit
            column = int(''.join([str(x) for x in block[1:][:-1]]),2) #Column is the 2,3,4,5th bits
            val = S_BOX[i][row][column] #Take the value in the SBOX appropriated for the round (i)
            bin = binvalue(val, 4)#Convert the value to binary
            result += [int(x) for x in bin]#And append it to the resulting list
        return result
        
    def permut(self, block, table):#Permut the given block using the given table (so generic method)
        return [block[x-1] for x in table]
    
    def expand(self, block, table):#Do the exact same thing than permut but for more clarity has been renamed
        return [block[x-1] for x in table]
    
    def xor(self, t1, t2):#Apply a xor and return the resulting list
        return [x^y for x,y in zip(t1,t2)]
    
    def generatekeys(self):#Algorithm that generates all the keys
        self.keys = []
        key = string_to_bit_array(self.password)
        key = self.permut(key, CP_1) #Apply the initial permut on the key
        g, d = nsplit(key, 28) #Split it in to (g->LEFT),(d->RIGHT)
        for i in range(16):#Apply the 16 rounds
            g, d = self.shift(g, d, SHIFT[i]) #Apply the shift associated with the round (not always 1)
            tmp = g + d #Merge them
            self.keys.append(self.permut(tmp, CP_2)) #Apply the permut to get the Ki
    def shift(self, g, d, n): #Shift a list of the given value
        return g[n:] + g[:n], d[n:] + d[:n]    
    def addPadding(self):#Add padding to the datas using PKCS5 spec.
        pad_len = 8 - (len(self.text) % 8)
        self.text += pad_len * chr(pad_len)   
    def removePadding(self, data):#Remove the padding of the plain text (it assume there is padding)
        pad_len = ord(data[-1])
        return data[:-pad_len]    
    def encrypt(self, key, text, padding=False):
        return self.run(key, text, ENCRYPT, padding)   
    def decrypt(self, key, text, padding=False):
        return self.run(key, text, DECRYPT, padding)    
if __name__ == '__main__':
    key = "secret_k"
    text= "Computer"
    d = des()
    r = d.encrypt(key,text)
    r2 = d.decrypt(key,r)
    print("Ciphered: %r" % r)
    print("Deciphered: ", r2)


OUTPUT

Ciphered: E\x97\x8a\x92\x1d\r\x98M
Deciphered: Computer



Wednesday, July 29, 2020

Write a Program Armstrong Number or Not in C++.

Armstrong Number or Not in C++.


#include<iostream>
using namespace std;
int main()
{
int arm=0,a,b,c,d,num;
cout<<"Enter any num: ";
cin>>num;
d=num;
while(num>0)
{
a=num%10;
num=num/10;
arm=arm+a*a*a;
}
if(arm==d)
{
cout<<"It is Armstrong";
}
else
{
cout<<"It is not Armstrong";
}
return 0;
}


OUTPUT

Enter any num: 371
It is Armstrong

Write a Program find Palindrome or Not in C++.

Palindrome or Not in C++.


#include <iostream>
using namespace std;
int main()
{
int n,s,sum=0,temp;
cout<<"Enter the Number=";
cin>>n;
temp=n;
while(n>0)
{
s=n%10;
sum=(sum*10)+s;
n=n/10;
}
if(temp==sum)

cout<<"Number is Palindrome :";
else
cout<<"Number is not Palindrome :";
return 0;
}


OUTPUT

Enter the Number=121
Number is Palindrome.

Write a Program find Factorial Number in C++.

Factorial Number in C++.


#include<iostream>
using namespace std;
int main()
{
int i, no, fact=1;
cout<<"Enter the any no. : ";
cin>>no;
for(i=1;i<=no;i++)
{
fact=fact*i;
}
cout<<"Factorial: "<<fact;
return 0;
}
OUTPUT

Enter the any no. : 5
Factorial: 120

Write a Program find Next Prime number in C++.

Next Prime number in C++.


#include<iostream>
using namespace std;
int main()
{
int p,q=2,number;
cout<<"Enter any num: ";
cin>>number;
cout<<"Next prime num: ";
for(p=number+1;p<3000;p++)
{
for(q=2;q<p;q++)
{
if(p %q==0)
{
break;
}
}
if(p==q || p==1)
{
cout<<"\t"<<p;
break;
}
}
return 0;
}


OUTPUT

Enter any num: 21
Next prime num: 23

Write a Program to Check Whether a character is Vowel or Consonan in C++.

Vowel or Consonan in C++.


#include <iostream>
using namespace std;
int main()
{
char ch;
int Low, Upp;
cout << "Enter an alphabet: ";
cin >> ch;
Low = (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
Upp = (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U');
if (Low || Upp)
cout << ch << " is a vowel.";
else
cout << ch << " is a consonant.";
return 0;
}



OUTPUT

Enter an alphabet: A
A is a vowel.

Write a Program Swap two numbers without using third variable in C++.

Swap two numbers without using third variable in C++.


#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"After swap a: "<<a<<"b: "<<b;
return 0;
}


OUTPUT

Enter value of a: 19
Enter value of b: 28

    After swap a: 28 b: 19

Write a Program Swap Two Numbers Program in C++.

Swap Two Numbers Program in C++.

#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter value of a:\n";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
c=a;
a=b;
b=c;
cout<<"After swap a: "<<a<<"b: "<<b;
return 0;
}

OUTPUT

Enter value of a:
28
Enter value of b: 19
After swap a: 19 b: 28

Write a program to Division of two number in C++.

Division of two number in C++.

#include<iostream>
using namespace std;
int main()
{
int a,b,div;
cout<<"Enter the First number :\n";
cin>>a;
cout<<"Enter the Second number :\n";
cin>>b;
div=a/b;
cout<<"Division by two number "<<div;
return 0;
}

OUTPUT

Enter the First number
38
Enter the Second number
2
Division by two number 19

Write a program to multiplication of two number in C++.

Multiplication of two number in C++.


#include<iostream>
using namespace std;
int main()
{
int a,b,mul;
cout<<"Enter the First number\n";
cin>>a;
cout<<"Enter the Second number\n";
cin>>b;
mul=a*b;
cout<<"Multiply by two number "<<mul;
return 0;
}

OUTPUT

Enter the First number
34
Enter the Second number
2
Multiply by two number 68

Write a program to subtraction of two number in C++.

Subtraction of two number in C++.


#include<iostream>
using namespace std;
int main()
{
int a,b,sub;
cout<<"Enter the First number :\n";
cin>>a;
cout<<"Enter the Second number :\n";
cin>>b;
sub=a-b;
cout<<"Subtraction of two number "<<sub;
return 0;
}

OUTPUT

Enter the First number
55
Enter the Second number
36
Subtraction of two number 19

Tuesday, July 28, 2020

Write a Program Hello World in C++.

Hello World  in C++


#include <iostream>
using namespace std;
int main() 
{
    cout << "Hello World!!!\n";
    return 0;
}

OUTPUT

Hello World!!!


Write a Program Check Even or Odd in C++.

Check Even or Odd in C++.


#include<iostream>
using namespace std;

int main()
{
int number;
cout<<"Enter a number ::";
cin>>number;
if(number%2==0)
{
cout<<"This is an even number \n";
}
else
{
cout<<"This is an odd number \n";
}
return 0;
}

OUTPUT

Enter a number :: 75
This is an Odd Number 

Write a Program to Add Two Integers in C++.

Add Two Integers in C++.

#include <iostream>
using namespace std;

int main()
{
    int fst, sec, sum;
    cout << "Enter two integers ::\n ";
    cin >> fst >> sec;
    sum = fst + sec;
    cout << fst << " + " <<  sec << " = " << sum;     

    return 0;
}

OUTPUT

Enter two integers ::
 5
 5
5 + 5 = 10

Write a Program to Check Armstrong Number in Python.

Armstrong Number in Python.

Armstrong number is a number such that the sum ! of its digits raised to the third power is equal to the number ! itself. For example, 153 is an Armstrong number.

number = int(input("Enter a number ::"))
sum = 0
temp = number
while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10
if number == sum:
   print(number,"is an Armstrong number >")
else:
   print(number,"is not an Armstrong number >")


OUTPUT

Enter a number ::153
153 is an Armstrong number >

Write a Program to Print the Fibonacci sequence in Python.

 Fibonacci sequence in Python.

The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers .

ms = int(input("Enter a Number :: "))

num1, num2 = 0, 1
count = 0

if ms <= 0:
   print("Please enter a positive integer")
elif ms == 1:
   print("Fibonacci sequence upto",ms,"::")
   print(num1)
else:
   print("Fibonacci sequence:")
   while count < ms:
       print(num1)
       n = num1 + num2
       num1 = num2
       num2 = n
       count += 1

OUTPUT

Enter a Number :: 7
Fibonacci sequence:
0
1
1
2
3
5
8

Write a Program to Find the Factorial of a Number in Python.

Factorial of a Number in Python.


The 
factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1. Examples: 5! = 5 x 4 × 3 × 2 × 1 = 120;


number = int(input("Enter a number :: "))  
fact = 1  
if number < 0:  
   print("Factorial does not exist for negative numbers")  
elif number == 0:  
   print("The factorial of 0 is 1")  
else:  
   for i in range(1,number + 1):  
       fact = fact*i  
   print("The factorial of",number,"is",fact)  


OUTPUT

Enter a number :: 5
The factorial of 5 is 120


Monday, July 27, 2020

Write a Program to Display the multiplication Table in Python.

Multiplication Table in Python.


num = int(input("Show the multiplication table : "))  
# multiplication 10 times   
for i in range(1,11):  
   print(num,'*' ,i ,'=', num*i) 

OUTPUT

10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
 10 * 10 = 100

Write a Program to Check Prime Number in Python.

Check Prime Number in Python.


number = int(input("Enter a number :: "))  
  
if number > 1:  
   for i in range(2,number):  
       if (number % i) == 0:  
           print(number,"is not a prime number")  
           print(i,"times",number//i,"is",number)  
           break  
   else:  
       print(number,"is a prime number")  
         
else:  
    print(number,"is not a prime number")  


OUTPUT

Enter a number :: 631
631 is a prime number


Write a Program to Check Leap Year in Python.

Check Leap Year in Python.

year = int(input("Enter a year :: "))  
if (year % 4) == 0:  
   if (year % 100) == 0:  
       if (year % 400) == 0:  
           print("{0} is a leap Year  ".format(year))  
       else:  
           print("{0} is not a leap Year  ".format(year))  
   else:  
       print("{0} is a leap Year  ".format(year))  
else:  
   print("{0} is not a leap Year  ".format(year))  


OUTPUT

Enter a year :: 1996
1996 is a leap Year 



Write a Program to Check if a Number is Odd or Even in Python.

 Number is Odd or Even in Python.


number = int(input("Enter a number :: "))  
if (number % 2) == 0:  
   print("{0} is Even number :".format(number))  
else:  
   print("{0} is Odd number :".format(number))  


OUTPUT

Enter a number :: 58
58 is Even number :

Write a Program to check if a Number is Positive and Negative or Zero in Python.

Number is Positive and Negative or Zero in Python.


number = float(input("Enter a number :: "))  
  
if number > 0:  
 print("{0} is a positive number ".format(number))  
elif number == 0:  
   print("{0} is zero :".format(number))   
else:  
   print("{0} is negative number ".format(number))   


OUTPUT

Enter a number :: 25
25.0 is a positive number 

Write a Program to swap two variables in Python.

swap two variables in Python.


m = input('Enter value of m : ')  
s = input('Enter value of s : ')  

temp = m  
m = s  
s = temp  
  
print('The value of x after swapping :: {}'.format(m))  
print('The value of y after swapping :: {}'.format(s))  

OUTPUT

Enter value of m : 5
Enter value of s : 4

The value of x after swapping :: 4
The value of y after swapping :: 5


Write a Program to arithmetical operations in Python.

Arithmetical operations in Python.


number1 = input('Enter first number :: ')  
number2 = input('Enter second number :: ')  
  
# Add two numbers  

add = (number1) + (number2) 

# Subtract two numbers  

min = (number1) - (number2) 

# Multiplication two numbers  

mul = (number1) * (number2)  

#Division two numbers  

div = (number1) / (number2)  

# Display the Addition  

print('The Addition of {0} and {1} is {2}'.format(number1, number2, add))  
  
# Display the subtraction  

print('The subtraction of {0} and {1} is {2}'.format(number1, number2, min))  

# Display the multiplication  

print('The multiplication of {0} and {1} is {2}'.format(number1, number2, mul))  

# Display the division  

print('The division of {0} and {1} is {2}'.format(number1, number2, div))

OUTPUT

Enter first number :: 20
Enter second number :: 3
        The Addition of 20 and 3 is : 23
              The subtraction of 20 and 3 is : 17
                 The multiplication of 20 and 3 is : 60
        The division of 20 and 3 is : 6

Write a Program to find the area of a triangle in Python.

Area of a triangle in Python.


x = float(input('Enter first side :: '))  
y = float(input('Enter second side :: '))  
z = float(input('Enter third side :: '))  
  
# Calculate the semi-perimeter  ..........

m = (x + y + z) / 2  
  
# Calculate the area  ..........

area = (m*(m-x)*(m-y)*(m-z)) ** 0.5  
print('The area of the triangle is : %0.2f' %area)   


OUTPUT

Enter first side :: 5
     Enter second side :: 4
Enter third side :: 7

The area of the triangle is :9.80



Saturday, July 25, 2020

Implement Hill cipher encryption-decryption in Python.

Hill cipher in Python

import numpy as np
import math
np.keyMatrix = [[0] * 3 for i in range(3)]
messageVector = [[0] for i in range(3)]
cipherMatrix = [[0] for i in range(3)]
plainMatrix = [[0] for i in range(3)]
np.inverseKeyMatrix = [[0] * 3 for i in range(3)]

def getKeyMatrix(key):
  k = 0
  for i in range(3):
    for j in range(3):
      np.keyMatrix[i][j] = ord(key[k]) % 65
      k += 1

def encrypt(messageVector):
  for i in range(3):
    for j in range(1):
      cipherMatrix[i][j] = 0
      for x in range(3):
        cipherMatrix[i][j] += (np.keyMatrix[i][x] * messageVector[x][j])
        cipherMatrix[i][j] = cipherMatrix[i][j] % 26

def HillCipher1(message, key):
  getKeyMatrix(key)
  for i in range(3):
    messageVector[i][0] = ord(message[i]) % 65
  encrypt(messageVector)
  CipherText = []
  for i in range(3):
    CipherText.append(chr(cipherMatrix[i][0] + 65))
  print("Ciphertext: ", "".join(CipherText))

def getInverseKeyMatrix(key):
  getKeyMatrix(key)
  keyMatrix=np.keyMatrix
  from sympy import Matrix
  inverseKeyMatrix = Matrix(keyMatrix).inv_mod(26)
  np.inverseKeyMatrix = np.array(inverseKeyMatrix)

def HillCipher2(message, key):
  getInverseKeyMatrix(key)
  for i in range(3):
    messageVector[i][0] = ord(message[i]) % 65
  decrypt(messageVector)
  PlainText = []
  for i in range(3):
    PlainText.append(chr(int(round(plainMatrix[i][0]) + 65)))
  print("Plaintext: ", "".join(PlainText))

def decrypt(messageVector):
  for i in range(3):
    for j in range(1):
      plainMatrix[i][j] = 0
      for x in range(3):
        plainMatrix[i][j] = plainMatrix[i][j] % 26
        plainMatrix[i][j] += (np.inverseKeyMatrix[i][x] * messageVector[x][j])
      plainMatrix[i][j] = plainMatrix[i][j] % 26

def main():
  message = input("Enter 3 no. of string :")
  message = message.upper()
  key = input("Enter the Key :")
  key = key.upper()
  ch1=int(input("1.Encryption\n2.Decryption\nEnter the choice ::"))
  if ch1 == 1:
    HillCipher1(message, key)
  elif ch1 == 2:
    HillCipher2(message,key)
  else:
    print("Wrong input")

if __name__ == "__main__": 
    main()

OUTPUT

Enter 3 no. of string :sms
Enter the Key :gybnqkurp

1.Encryption
2.Decryption

Enter the choice ::1
Ciphertext:  YIC

Implement Monoalphabetic cipher encryption-decryption in Python.

Monoalphabetic cipher in Python.


import sys, random
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def main():
    myMessage = 'All our dreams can come true, if we have the courage to pursue them'
    myKey = 'QWERTYUIOPASDFGHJKLZXCVBNM'
    myMode = 'encrypt' 

    checkValidKey(myKey)

    if myMode == 'encrypt':
        translated = encryptMessage(myKey, myMessage)
    elif myMode == 'decrypt':
        translated = decryptMessage(myKey, myMessage)
    print('Using key : %s' % (myKey))
    print('The %sed message is :' % (myMode))
    print(translated)


def checkValidKey(key):
    keyList = list(key)
    lettersList = list(LETTERS)
    keyList.sort()
    lettersList.sort()
    if keyList != lettersList:
        sys.exit('There is an error in the key or symbol sets.')


def encryptMessage(key, message):
    return translateMessage(key, message, 'encrypt')


def decryptMessage(key, message):
    return translateMessage(key, message, 'decrypt')


def translateMessage(key, message, mode):
    translated = ''
    chA = LETTERS
    chB = key
    if mode == 'decrypt':
    
        chA, chB = chB, chA

    
    for symbol in message:
        if symbol.upper() in chA:
           
            symIndex = chA.find(symbol.upper())
            if symbol.isupper():
                translated += chB[symIndex].upper()
            else:
                translated += chB[symIndex].lower()
        else:
            
            translated += symbol

    return translated


def getRandomKey():
    key = list(LETTERS)
    random.shuffle(key)
    return ''.join(key)

main()

OUTPUT

Using key : QWERTYUIOPASDFGHJKLZXCVBNM

The encrypted message is :

Qss gxk rktqdl eqf egdt zkxt, oy vt iqct zit egxkqut zg hxklxt zitd