I'm trying to solve 56th problem of Project Euler and I have some troubles while using the Big Integer Library. Here is the code :
#include <iostream>
#include "BigInteger.hh"
#include <cmath>
using namespace std;
int digitSum(BigInteger x){
int num[(int)floor(log10(x))+2];
int n = 0;
BigInteger sum = 0;
while (x != 0){
sum += x - floor(x/10) * 10;
x = floor(x/10);
n++;
}
return sum.toInt();
}
int main(int argc, const char * argv[])
{
int max = 0;
for (int i = 1; i <= 100; i++){
for (int j = 1; j <= 100; j++){
cout << "i = %i, j = %i ",i,j;
if (digitSum(pow(i,j)) < max)
max = digitSum(pow(i,j));
}
}
cout << digitSum(pow(2,63));
return 0;
}
The problem is that when I try building, the compiler gives error on the lines using the log10, floor, and pow functions saying that they are used but not defined. When I comment the line #include "BigInteger.hh", everything goes fine but this time, of course, I can't use the Big Integer library.
Why is there such a problem? How to solve it?
Is it a compiler or a linker problem? If latter, try adding -lm to the command line to link the math library. Assuming GNU gcc here.
Related
I am trying to initialise two 2D arrays, namely psi_0 and omega_0, with the data type as double. The sizes of the arrays are 401x401. I have written the last printing statement to check if the code is running properly or not. As soon as I initialise arrays, the last line doesn't get printed and this is getting displayed only: PS C:\Users\Avii\Desktop> cd "c:\Users\Avii\Desktop\" ; if ($?) { g++ trialc++.cpp -o trialc++ } ; if ($?) { .\trialc++ }.
Following is my code:
#include<iostream>
#include<iomanip>
#include <math.h>
#include <vector>
#include <algorithm>
#include <thread>
#include <chrono>
using namespace std;
void display(vector<double> &v){
for (int i = 0; i < v.size(); i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
}
int main(){
const int N = 401;
const double pi = 3.141592653589793;
double L = pi/2;
double r = 1.5;
//-------------------------------------------------------------------
.
..
...
double psi_0[N][N];
double omega_0[N][N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
psi_0[i][j] = sin(x_vec[i]) * (sin(y_vec[j]));
omega_0[i][j]= 2 * sin(x_vec[i]) * sin(y_vec[j]);
}
}
cout<< "everything is fine"; // to check if the code has run till last or not!
return 0;
}
Here x_vec and y_vec are two vectors of size 401 and data type as double. I have tried using flush but could not see the problem is solved!
Any help is highly appreciated!!
My code goes through the values of each sample in a JSON file and gives out the number of sorting comparisons, the amount of memory, and time it takes for the sorting to happen. But for some reason the code is throwing me an error. Would love it if someone could help me out.
I'm getting a [json.exception.type_error.302] for some reason in my code. I know what the error means but I don't know where there's a fault
To be exact, this is the error I'm getting - "libc++abi.dylib: terminating with uncaught exception of type nlohmann::detail::type_error: [json.exception.type_error.302] type must be number, but is null"
#include <iostream>
#include <fstream>
#include "json.hpp"
#include "mergesort.h"
#include "insertionsort.h"
#include "quicksort.h"
#include <ctime>
#include <iomanip>
int main(int argc, char* argv[]) {
std::ifstream file;
file.open(argv[1]);
nlohmann::json jsonObject;
if (file.is_open()) {
file >> jsonObject;
} else {
std::cout << "Invalid Argument" << std::endl;
}
clock_t mergeTime, quickTime, insertTime;
extern int insertMemAccesses, insertCompare, mergeMemAccesses, mergeCompare, quickCompare, quickMemAccesses;
// std::cout << jsonObject;
// nlohmann::json jsonOutput;
std::cout << "Sample,InsertSortTime,InsertionSortCompares,InsertionSortMemaccess,MergeSortCompares,MergeSortMemaccess,QuickSortTime,QuickSortCompares,QuickSortMemaccess";
int arraysize = jsonObject["metadata"]["arraySize"];
int numsamples = jsonObject["metadata"]["numSamples"];
for (int i = 0; i <= numsamples; i++) {
std::string sample;
if (i < 9) {
sample = "Sample0" + std::to_string(i+1);
} else {
sample = "Sample" + std::to_string(i+1);
}
std::vector<int> insertion;
std::vector<int> merge;
std::vector<int> quick;
for(int j = 0; j <= arraysize; j++){
insertion.push_back(jsonObject[sample][j]);
merge.push_back(jsonObject[sample][j]);
quick.push_back(jsonObject[sample][j]);
}
insertTime = clock();
InsertionSort(&insertion);
insertTime = clock() - insertTime;
insertTime = ((unsigned long)insertTime)/CLOCKS_PER_SEC;
mergeTime = clock();
MergeSort(&merge);
mergeTime = clock() - mergeTime;
mergeTime = ((unsigned long)mergeTime)/CLOCKS_PER_SEC;
quickTime = clock();
QuickSort(&quick);
quickTime = clock() - quickTime;
quickTime = ((unsigned long)quickTime)/CLOCKS_PER_SEC;
std::cout<<sample<<",";
printf("%.6lu,%d,%d,%.6lu,%d,%d,%.6lu,%d,%d\n",insertTime,insertCompare,insertMemAccesses,mergeTime,mergeCompare,mergeMemAccesses,quickTime,quickCompare,quickMemAccesses);
insertCompare = 0;
insertMemAccesses = 0;
mergeCompare = 0;
mergeMemAccesses = 0;
quickCompare = 0;
quickMemAccesses = 0;
}
return 0;
}
Step through the code, and which line does the exception happen on? If you don't have a way to step through, then add in some std::cerr calls throughout to see where it is failing. I would assume that the error occurs on one of the push_back lines, most likely the first. You have j <= arraysize, which most likely goes out of bounds, so when you try to access jsonObject[sample][arraysize] this causes the error.
Also, you could probably just do quick = merge = insertion = jsonObject[sample].get<std::vector<int>>(), instead of needing the loop
This is probably a very easy problem, but I am studying while loops and I am trying to write a program that sums numbers from 50 to 100. This is my code that I wrote
#include <iostream>
using namespace std;
int main() {
int sum=0;
int val=1;
while(50 <= val <= 100) {
sum = sum + val;
val = val + 1;
}
cout << "Sum is: " << sum << endl;
return 0;
}
I was to compile the code and get a program, but each time I am trying to run the program on terminal is just goes idle. Is there something wrond with my code? Thanks!
All the comments are valid. Please look at the C++ reference for syntax and how to use operators and loop.
I believe looking at some correct code is also a way to learn and hence posting this :
#include <iostream>
using namespace std;
int main ()
{
int sum = 0;
int i = 50; // Why not start from 50 itself, when you want sum(50-100)
while (i <=100)
{
sum += i; // Same as sum = sum + i
i++; // Same as i = i + 1
}
cout<<sum<<"\n";
return 0;
}
Why doesn't the following code work? It prints INT_MAX. But if I uncomment the two lines in the inner for loop, then it works fine (prints 2). I can't combine the two macros like that? Not sure if further detail is needed...pretty self explanatory.
Thanks.
#include <iostream>
#include <limits.h>
using namespace std;
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
int main(int argc, char **argv)
{
int N = 100;
int *drop = new int[N+1];
drop[0] = 0; drop[1] = 1; drop[2] = 1;
for(int i=3; i<=N; i++)
{
drop[i] = INT_MAX;
for(int start=1; start<=i; start++)
{
drop[i] = min(drop[i], max(start, drop[i-start]+1));
//int x = max(start, drop[i-start]+1);
//drop[i] = min(drop[i], x);
}
}
cout<<drop[3]<<endl;
return 0;
}
Put brackets around the terms in your macros:
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
As it is, this:
drop[i] = min(drop[i], max(start, drop[i-start]+1));
is expanding to this (without brackets):
drop[i] < start > drop[i-start]+1 ? start: drop[i-start]+1 ? drop[i] : start > drop[i-start]+1 ? start: drop[i-start]+1;
which may not evaluate in the order you intend. Using brackets enforces the correct order of operations.
As noted in the comments, you shouldn't use macros with expressions that have side effects if the macro arguments are evaluated more than once.
C++ already has std::min and std::max defined in <algorithm>. You can change your code to a pure C++ version
#include <iostream>
#include <algorithm>
#include <limits>
using namespace std;
int main(int argc, char ** argv) {
int N = 100;
int * drop = new int[N + 1];
drop[0] = 0;
drop[1] = drop[2] = 1;
for (int i = 3; i <= N; ++i) {
drop[i] = numeric_limits<int>::max(); // <limits>
for(int start = 1; start <= i; ++start)
drop[i] = min(drop[i], max(start, drop[i - start] + 1)); // <algorithm>
}
cout << drop[3] << endl;
return 0;
}
Rather than an answer, it's a plead to all developers out there: please don't use macros like that. C++ offers template functions for these purposes. Remember that macros just substitute parameters rather than pre-evaluating them. Even if you add parentheses as samgak explained, this only fixes a half of the problem. Consider code like this:
int x = 5;
int y = max(++x, 0);
The caller would expect x=6 and y=6 after that; however the macro will get expended into
int y = (++x > 0)? ++x : 0;
causing x=7 and y=7.
Hello i have a code like this:
#include <iostream>
#include <cstdio>
using namespace std;
int main () {
std::string s="fawwaz";
...
}
then i compiled it with G++ using the gnu gcc online installer i've downloaded from gcc.gnu.org, The compilation runs without any errors and warnings, but when i run, an error appears "program a.exe has stopped working".
and the program runs without any error. Then i try to compile the original file (without double backslash infront of string declaration) the program compiled and run succesfully.
Whats the solution? Where's the problem? Is they any way to fix my problem so i can compile my program via command line NOT via Microsoft Visual C++ since it would be faster to compile via command line? :D
Thank you
This is the complete code :
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void Cetak_Puzzle_Start(){
}
int main(int argc, char const *argv[])
{
string s;
ifstream file("input.txt");
vector<vector<int> > Puzzle_Start;
vector<vector<int> > Puzzle_Finish;
int Puzzle_size=0;
/*
* RETRIEVE PUZZLE SIZE
**/
getline(file,s);
for (int i = 0; i < s.length(); ++i)
Puzzle_size= (Puzzle_size*10) + (int) (s[i]-'0');
/*
* Set Zero ukuran 3x3 vector Puzzle start dan Puzzle finish
**/
vector<int> vtemp(Puzzle_size,0);
for (int i = 0; i < Puzzle_size; ++i)
{
Puzzle_Start.push_back(vtemp);
Puzzle_Finish.push_back(vtemp);
}
/*
* RETRIEVE START STATE
**/
getline(file,s);
int m=0,n=0; // dummy var for looping only m:pointer baris, n:pointer kolom,
for (int i = 0; i < s.length(); ++i)
if (n<Puzzle_size){
if (s[i]=',')
n++;
else if (s[i] >= '0' && s[i] <='9')
Puzzle_Start[m][n]= (Puzzle_Start[m][n] * 10) +(int) (s[i]-'0');
else if (s[i] ='B')
Puzzle_Start[m][n]=-1;
}else{
n=0; // Ganti baris
m++;
}
fclose(stdin);
/*
* CETAK PUZZLE
**/
// for (int i = 0; i < Puzzle_Start.size(); ++i){
// for (int j = 0; j < Puzzle_Start[i].size(); ++j)
// printf("%d ",Puzzle_Start[i][j]);
// printf("\n");
// }
return 0;
}
Here's the bug,
if (s[i]=',')
should be
if (s[i]==',')
and
else if (s[i]='B')
should be
else if (s[i]=='B')
Confusing = (assignment) and == (equality) is a very common error to make