Convert this C++ code to Java code please attach samples run of the code #includ
ID: 3806622 • Letter: C
Question
Convert this C++ code to Java code
please attach samples run of the code
#include <stdio.h>
#include<iostream.h>
#include <conio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
main()
{
long int p,g,Sa=0,Sb=0,Ta,Tb,Skey1,Skey2,Skey;
clrscr();
cout<<"Enter a Value for p :";
cin>>p;
cout<<" Enter a Value for g :";
cin>>g;
//======== Generate Sa and Sb Values Randomly between 0 and 20
Sa=random(20);
Sb=random(20);
//======== Calculate Ta and Tb Values
Ta=(pow(g,Sa));
Ta=Ta%p;
Tb=(pow(g,Sb));
Tb=Tb%p;
//======== Calculate Secret Key Values
Skey1=(pow(Tb,Sa));
Skey1=Skey1%p;
Skey2=(pow(Ta,Sb));
Skey2=Skey2%p;
if(Skey1==Skey2)
Skey=Skey1;
//========= Print Secret Key Value
cout<<" The random Number of SA is :"<<Sa;
cout<<" The random Number of SA is :"<<Sb;
cout<<" The Value of Secret Key is :"<<Skey;
getch();
return 0;
}
Explanation / Answer
HI, Please find my implementation in Java.
Please let me know in case of any issue.
import java.util.Random;
import java.util.Scanner;
public class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long p,g,Ta,Tb,Skey1,Skey2,Skey = 0;
int Sa=0,Sb=0;
Random random = new Random();
System.out.print("Enter a Value for p :");
p = sc.nextLong();
System.out.print("Enter a Value for g : ");
g = sc.nextLong();
//======== Generate Sa and Sb Values Randomly between 0 and 20
Sa = random.nextInt(21); //0-20
Sb = random.nextInt(21); //0-20
//======== Calculate Ta and Tb Values
Ta=(long)(Math.pow(g,Sa));
Ta=Ta%p;
Tb=(long)(Math.pow(g,Sb));
Tb=Tb%p;
//======== Calculate Secret Key Values
Skey1=(long)(Math.pow(Tb,Sa));
Skey1=Skey1%p;
Skey2=(long)(Math.pow(Ta,Sb));
Skey2=Skey2%p;
if(Skey1==Skey2)
Skey=Skey1;
//========= Print Secret Key Values
System.out.println("The random Number of SA is : "+Sa);
System.out.println("The random Number of SA is : "+Sb);
System.out.println("The Value of Secret Key is : "+Skey);
}
}
/*
Sample run:
Enter a Value for p :23
Enter a Value for g : 21
The random Number of SA is : 4
The random Number of SA is : 5
The Value of Secret Key is : 6
*/