我可以使用未签名的长阵列吗?

Can i use unsigned long long arrays

本文关键字:阵列 可以使 我可以      更新时间:2023-10-16

我试图在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的数组,则会导致不确定的行为。