我可以使用未签名的长阵列吗?
Can i use unsigned long long arrays
我试图在hackerrank上解决这个问题。
您有四个整数:n,s,p,q。您将使用它们来使用以下伪代码来创建序列。
a[0] = S (modulo 2^31)
for i = 1 to N-1
a[i] = a[i-1]*P+Q (modulo 2^31)
您的任务是计算序列中不同整数的数量。
Sample Input
3 1 1 1
Sample Output
3
Constraints
1<= N <= 10^8
0<= S,P,Q < 2^31
,这是我在C 中的解决方案。在大多数情况下,我都会得到分割故障..我知道这应该是使用位数组来解决的。.但想知道为什么这是不起作用的。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
unsigned long long n,s,p,q;
cin >> n >> s >> p >> q;
//declaring array to hold sequence
unsigned long long a[n];
// for loop termination
bool termination_check = true;
//initializing sequence
//s<2^31 hence, s modulo 2^31 is always s
a[0] = s;
//creating sequence
for(int i=1;i<n;i++){
//calculating next term of sequence..
a[i] = (a[i-1]*p)+q;
//since a[i] modulo 2^31 is a[i] when a[i] < 2^31
if(a[i]>=pow(2,31)){
a[i] = a[i]%31;
//when the current term matches with any of previous terms of sequence, then the
//terms just repeat after that (since p and q are constants)
for(int j=0;j<i;j++){
if(a[i]==a[j]){
cout <<i << endl;
//i was trying to use break but dont know why, it did not work
termination_check = false;
break;
break;
}
}
}
}
//if there was no termination of loop then all the terms are distinct
if(termination_check){
printf("%llu n", n);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
是的,您可以在C 中具有unsigned long long
数组。但是您所拥有的不是数组:unsigned long long a[n];
要求n
是常数。(在C中这会有所不同,但是您正在编写C )。
它仍然是一个编译器扩展程序,可让您混合C和C ,但是行为未定义。特别是缺乏错误处理的错误。
此答案是针对以前版本的代码。该代码现在已在问题中进行了编辑(j = i和i = n被两个休息所取代)
查看遇到情况时发生的事情
a[i] == a[j]
您将j
设置为i
,然后将i
设置为n
。但是i
小于n
,因此语句j<i
仍然是正确的。然后,您的循环继续运行,因此您的程序M试图评估
a[i] == a[j]
有了您分配的新值,您实际上是在询问
是否a[n] == a[i]
但是,如果您的数组a
是大小n
的数组,则会导致不确定的行为。
相关文章:
- 如何修复阵列以使其正确?
- 是否可以使C++类成为Objc类的委托
- 是否可以使一个类成为两个不同层次结构的子类?
- 我有一系列阵列.可以从一个数组中阅读一些元素和另一个数组中的其他元素
- 是否有编译器标志可以使较新的 gcc 版本像旧版本一样构建
- C 可以使destuructor不称为班级成员和基类攻击方的灾难
- 排序阵列会使指针链接错误
- 可以使未命名的结构静态
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- C++:有哪些常规方法可以使代码更有效地用于大数字
- 是否可以使 std 容器使用默认运算符为新?
- LD_BIND_NOW可以使可执行文件运行得更慢?
- 是否可以使头文件使文本居中?- 在控制台中
- 有什么方法可以使核心忙碌等待
- 有没有一种技术可以使虚函数在所有派生类中强制重写?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 是否有一种方法可以使此C 14递归模板在C 17中短
- 编写一个可以使二维数组平坦的函数
- 有哪些优化技巧可以使我的代码运行得更快
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具