BigInteger java method to gmp c++ - c++

I want to convert java code in c++
code is
BigInteger value = new BigInteger(125, RandomNumber);
BigInteger clone = new BigInteger(value.toByteArray());
How to write this code in cpp using gmp library?
Please anyone help me.
Thanks.

With C++ you can do that
#include <gmpxx.h>
#include <gmp.h>
#include <iostream>
using namespace std;
int main(){
mpz_class value;
mpz_class clone;
gmp_randclass r(gmp_randinit_default);
value = r.get_z_bits(125);
clone = value;
cout << value << endl;
cout << clone << endl;
return 0;
}
and compile with
g++ file.cpp -lgmpxx -lgmp
to install libgmpxx.a
put --enable-cxx to the build option of ./configure

here is a carbon copy from wikipedia
Here is an example of C code showing the use of the GMP library to multiply and print large numbers:
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(void)
{
mpz_t x;
mpz_t y;
mpz_t result;
mpz_init(x);
mpz_init(y);
mpz_init(result);
mpz_set_str(x, "7612058254738945", 10);
mpz_set_str(y, "9263591128439081", 10);
mpz_mul(result, x, y);
gmp_printf("\n %Zd\n*\n %Zd\n--------------------\n%Zd\n\n", x, y, result);
/* free used memory */
mpz_clear(x);
mpz_clear(y);
mpz_clear(result);
return EXIT_SUCCESS;
}
This code calculates the value of 7612058254738945 × 9263591128439081.
Compiling and running this program gives this result. (The -lgmp flag is used if compiling on Unix-type systems.)
7612058254738945
*
9263591128439081
--------------------
70514995317761165008628990709545

Related

Want to print the hexadecimal value of a pointer as 'human readable' unsigned value

This is what I coded on Mobile C
#include <iostream>
using namespace std;
int main()
{
int i{14},j{20};
int *pj{&j},*pi{&i};
cout<<endl<<(unsigned)pi;
cout<<"\t"<<*pi;
cout<<endl<<(unsigned)pj;
cout<<"\t"<<*pj;
--pi;
++pj;
cout<<endl<<(unsigned)pi;
cout<<"\t"<<*pi;
cout<<endl<<(unsigned)pj;
cout<<"\t"<<*pj;
return 0;
}
And this was the output:
2582956840 14
2582956836 20
2582956836 20
2582956840 14
But when I'm trying to do this on visual code (fedora 36) and the terminal compiler g++ is throwing errors, as mentioned above in the Imgur image.
EDIT2:
I did this:
#include <iostream>
using namespace std;
int main()
{
unsigned int i{14},j{20};
unsigned int *pj{&j},*pi{&i};
cout<<endl<<(unsigned*)pi;
cout<<"\t"<<*pi;
cout<<endl<<(unsigned*)pj;
cout<<"\t"<<*pj;
--pi;
++pj;
cout<<endl<<(unsigned*)pi;
cout<<"\t"<<*pi;
cout<<endl<<(unsigned*)pj;
cout<<"\t"<<*pj;
return 0;
}
And got this output:
0x7fff539232d0 14
0x7fff539232d4 20
0x7fff539232cc 21863
0x7fff539232d8 1402090200
Strange! It was compiled using onlinegdb C++ compiler.
You can get the pointers value by doing this:
#include <iostream>
int main() {
int a = 2;
cout < &a;
}
This is pretty much as best you can do to make it human readable.
Also you can look at Displaying the address of a string if you want to look at any other approaches.

Program crashing with C++ DLL using OpenMP

I have a program using OpenMP on C++ and I need it to port into Dll so I can call it from Python. It returns an array of double values, which calculated using a lot of for loops with openmp pragma. I was doubtful if it is going to work, so I started from a little test program that calculates Pi value in a loop with different precision values, then I would measure performance and ensure that OpenMP works properly that way. Plain (w/o Omp) implementation works fine from Python and C++, however Omp variant gives a runtime error in Python (exception: access violation writing 0x000000000000A6C8) and crashes without an error in C++. Also Omp variant works fine if it is not a Dll and just a regular executable. The Dll is made with a makefile. App that uses the Dll built into an executable with g++ with no flags (source code is in UnitMain.cpp). All the relevant code and a Makefile below (I didn't include some files and functions for brevity).
UPD: I tried Microsoft compiler and it works, also I tested a linux dynamic library on WSL/g++ and it also works. Looks like it is Windows gcc specific, I'll try another version of gcc (btw my current version is this):
Thread model: posix gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
UnitFunctions.cpp
#include "UnitFunctions.h"
#include <omp.h>
#include <stdio.h>
#include <string.h>
typedef long long int64_t;
double pi(int64_t n) {
double sum = 0.0;
int64_t sign = 1;
for (int64_t i = 0; i < n; ++i) {
sum += sign/(2.0*i+1.0);
sign *= -1;
}
return 4.0*sum;
}
void calcPiOmp(double* arr, int N) {
int64_t base = 10e5;
#pragma omp parallel for
for(int i = 0; i < N; ++i) {
arr[i] = pi(base+i);
}
}
UnitMain.cpp
#include <windows.h>
#include <iostream>
using namespace std;
struct DllHandle
{
DllHandle(const char * const filename)
: h(LoadLibrary(filename)) {}
~DllHandle() { if (h) FreeLibrary(h); }
const HINSTANCE Get() const { return h; }
private:
HINSTANCE h;
};
int main()
{
const DllHandle h("Functions.DLL");
if (!h.Get())
{
MessageBox(0,"Could not load DLL","UnitCallDll",MB_OK);
return 1;
}
typedef const void (*calcPiOmp_t) (double*, int);
const auto calcPiOmp = reinterpret_cast<calcPiOmp_t>(GetProcAddress(h.Get(), "calcPiOmp"));
double arr[80];
calcPiOmp(arr, 80);
cout << arr[0] << endl;
return 0;
}
Makefile
all: UnitEntryPoint.o UnitFunctions.o
g++ -m64 -fopenmp -s -o Functions.dll UnitEntryPoint.o UnitFunctions.o
UnitEntryPoint.o: UnitEntryPoint.cpp
g++ -m64 -fopenmp -c UnitEntryPoint.cpp
UnitFunctions.o: UnitFunctions.cpp
g++ -m64 -fopenmp -c UnitFunctions.cpp
A Python script
import numpy as np
import ctypes as ct
cpp_fun = ct.CDLL('./Functions.dll')
cpp_fun.calcPiNaive.argtypes = [np.ctypeslib.ndpointer(), ct.c_int]
cpp_fun.calcPiOmp.argtypes = [np.ctypeslib.ndpointer(), ct.c_int]
arrOmp = np.zeros(N).astype('float64')
cpp_fun.calcPiOmp(arrOmp, N)

Codeblocks c++ undefined reference error, class is defined

Hey guys I asked a question the other day about some c++ code that I couldn't get to work. I took everyones advice as to how to create objects in c++ but now I get undefined reference errors. I am using the latest code blocks version and using that to compile. I have read that this is caused by not linking some files during compilation, and that it means I have defined the class in the header file but not in the code, which confuses me because from my understanding (a profs example) I am declaring the objects.
Header File
MathObject.h
class MathObject{
private:
int num1;
int num2;
public:
int sum();
MathObject(int n, int m);
};
MathObject file
MathObject.cpp
#include <iostream>
#include "MathObject.h"
using namespace std;
MathObject :: MathObject(int n, int m){
num1 = n;
num2 = m;
}
int MathObject :: sum(){
return num1+num2;
}
Main File
#include <iostream>
#include "MathObject.h"
using namespace std;
int main(int args, char *argv[]){
MathObject *mo = new MathObject(3,4);
int sum = mo -> sum();
MathObject mo2(3,4);
//cout << sum << endl;
return 0;
}
The undefined reference is for all calls to anything in the MathObject class, I have been searching for a small c++ example that I can understand. (The syntax is so different from java)
This used to happen when I tried to use multiple files in c, could this be an issue with my computer?
In the "Projects" tab in codeblocks, right-click your project's name and select "Add Files..."
Alternately, you can choose "Add files..." from "Project" in the application's main menu.
Use this to add all of your source files to your project.
Currently MathObject.cpp is missing from that list, so it's not getting compiled or linked.
g++ MathObject.cpp main.cpp -o main
Found a solution from code::blocks forum:
-Project -> "Build Options
-Make sure the correct target is highlighted on the left side; if you do not know select the project, top one.
-Select Tab "Search Directories"
-Select Sub-Tab "Compiler"
-"Add" the path to the folder that contains the header. Single Folder per line.
Just add your current folder or location of your header file to the path.
Link: http://forums.codeblocks.org/index.php?topic=14713.0
You can do this simply by adding .cpp file of the class in main.cpp.
#include <iostream>
#include "MathObject.h"
#include "MathObject.cpp"
using namespace std;
int main(int args, char *argv[]){
MathObject *mo = new MathObject(3,4);
int sum = mo -> sum();
MathObject mo2(3,4);
//cout << sum << endl;
return 0;
}
To fix undefined reference error :-
Settings -> compiler... -> Build options
finally mark "Explicitly add currently compiling file's directory to compiler search dirs"
I try this and works fine!
MAIN.cpp
#include <iostream>
#include "MathObject.h"
using namespace std;
int main(int args, char *argv[]){
MathObject *mo = new MathObject(3,4);
int sum = mo->sum();
MathObject mo2(3,4);
int sum2 = mo2.sum();
cout << sum << endl;
cout << sum2 << endl;
system("pause");
return 0;
}
MathObject.h
class MathObject
{
private:
int num1;
int num2;
public:
MathObject(void);
~MathObject(void);
int sum();
MathObject(int n, int m);
};
MathObject.cpp
#include "MathObject.h"
MathObject::MathObject(void)
{
}
MathObject::~MathObject(void)
{
}
int MathObject::sum(){
return num1+num2;
}
MathObject::MathObject(int n, int m){
num1 = n;
num2 = m;
}
Compile with:
g++ MathObject.cpp main.cpp -o main.exe

Cannot build C++ code using lapack

I wrote a simple code to test boost and lapack
But it doesn't work well
My code :
#include < iostream>
#include < boost/numeric/bindings/traits/ublas_matrix.hpp>
#include < boost/numeric/ublas/matrix.hpp>
#include < boost/numeric/bindings/lapack/syev.hpp>
#include < boost/numeric/ublas/io.hpp>
namespace ublas = boost::numeric::ublas;
namespace lapack = boost::numeric::bindings::lapack;
int main() {
ublas::matrix<double> A(3,3);
ublas::vector<double> B(3);
A(0,0)=1;
A(1,1)=2;
A(2,2)=4;
A(0,1)=.5;
A(0,2)=.25;
A(1,2)=.3;
lapack::syev('V','L',A,B);
std::cout << A << std::endl;
return 0;
}
My option g++ to build on ubuntu 10.04
g++ -llapack test.cpp
It's error :
no matching function for call to ‘syev(char....... )‘
If there's not "lapack::syev('V','L',A,B);" It's build okay!
Plz Help me !!
Please install the libboost-all-dev package.

Why is my program giving a totally different output when I compile with mingw as compared to g++

So when i compile this code (using the mersenne twister found here: http://www-personal.umich.edu/~wagnerr/MersenneTwister.html ):
#include <iostream>
#include <cmath>
#include "mtrand.h"
using namespace std;
double pythag(double x, double y) {
double derp=0;
derp=(x*x)+(y*y);
derp=sqrt(derp);
}
int main() {
double x=0;
double y=0;
double pi=0;
double hold1=0;
double hold2=0;
double hits=0;
MTRand mt;
mt.seed();
// cout.precision(10);
for(long i=1; i<=100000000000l; i++) {
x=abs(mt.rand());
y=abs(mt.rand());
if(pythag(x,y)<=1) {
hits++;
}
if(i%100000l==0) {
pi=(4*hits)/i;
cout << "\r" << i << " " << pi ;
}
}
cout <<"\n";
return 42;
}
Using g++ ("g++ pi.cc -o pi")
And run the resulting application, I get the output i wanted, a running tally of pi calculated using the Monte Carlo method.
But, when i compile with mingw g++ ("i686-pc-mingw32-g++ -static-libstdc++ -static-libgcc pi.cc -o pi.exe")
I always get a running tally of 0.
Any help is greatly appreciated.
Perhaps it's because you omitted the return statement:
double pythag(double x, double y) {
double derp=0;
derp=(x*x)+(y*y);
derp=sqrt(derp);
// You're missing this!!!
return derp;
}
I'd be surprised that you didn't get any warnings or errors on this.
pythag() does not return anything, as Loki is trying to say without telling you the exact answer. That means the return value is not specified.
Why do you return 42 in main()?! 8-)