为什么我会遇到大整数的分段错误



我写了一个代码如下:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
long long int n,s,p,q,i;
cin>>n>>s>>p>>q;
long long int a[n];
a[0] = s%(long long int)pow(2,31);
for(i=1;i<n;i++)
{
a[i] = a[i-1]*p+s%(long long int)pow(2,31);
}
long long int count=1;
for(i=1;i<n;i++)
{
if(a[i]!=a[i-1])
count++;
}
cout<<count;
return 0;
}

当我将输入作为时,我得到了分割错误

100151543 5115 5153 531stderr如下:

Reading symbols from Solution...done.
[New LWP 134199]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00000000004010f1 in main () at Solution.cpp:13
13      a[0] = s%(long long int)pow(2,31);
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
info "(gdb)Auto-loading safe path"

问题是黑客行为:https://www.hackerrank.com/challenges/bitset-1/problem

long long int a[n];

不会对你有任何好处,就像大家说的那样,最好使用矢量,你的代码应该看起来像这样:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
long long int n,s,p,q,i;
cin>>n>>s>>p>>q;
vector<long long int> a;
a.resize(n);
a[0] = s%(long long int)pow(2,31);
for(i=1;i<n;i++)
{
a[i] = a[i-1]*p+s%(long long int)pow(2,31);
}
long long int count=1;
for(i=1;i<n;i++)
{
if(a[i]!=a[i-1])
count++;
}
cout<<count;
return 0;
}

相关内容

  • 没有找到相关文章

最新更新