如何存储多达1,000,000,000个元素 [英] how to store upto 1,000,000,000 elements

查看:107
本文介绍了如何存储多达1,000,000,000个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int max_b(int,int);
int max(int[],int);

int main(){

    int num_tests;
    scanf("%d",&num_tests);
    int array_n[num_tests];
    int array_b[num_tests];
    int i,j;
    for (i=0;i<num_tests;i++){
        scanf("%d %d",&array_n[i],&array_b[i]);
    }
    for (j=0;j<num_tests;j++){
        int A = 1;
        int N = array_n[j];
        int B = array_b[j];
        int max_num_b;
        max_num_b = max_b(N,B);
        int array2[max_num_b];
        int k;
        for (k=0;k<max_num_b;k++){
            int num_a,num_b;
            num_a = N-(k+1)*B;
            num_b = k+1;
            array2[k] = num_a*num_b;            
        }
        printf("%d\n",max(array2,max_num_b));
    }

}

int max(int array[],int a){
    int max_num = 0,i;
    for (i=0;i<a;i++){
        if (array[i] > max_num){
            max_num = array[i];
        }
    }
    return max_num;
}

int max_b(int n,int b){
    return n/b;
}

我的第一个输入是测试用例T的数量(例如1),第二个是输入为1,000,000,000 1。因此,然后代码尝试形成10 ^ 9大小的数组,程序最终显示分段错误。但是,代码可以很好地运行至1,000,000 1.我如何存储多达10 ^ 9个元素。如果不可能的话,我怎么能存储这么多数字。
我应该使用malloc,如果是,那么如何使用。

my first input is num of test cases T (say 1),and second input is 1,000,000,000 1 . So then the code tries to form an array of 10^9 size and the program ends up showing segmentation fault. However the code runs well upto 1,000,000 1. how can I store upto 10^9 elements. If its not possible then how can I store so many numbers. Should I use malloc, if yes then how. any help would be appreciated.

推荐答案

您根本不需要存储这些数据。

You don't need to store this data at all. Just process it on the fly.

据我所知,以下代码产生的结果与您发布的代码相同,但是不使用任何数组。

As far as I can tell, the following code produces the same results as the code you posted, but uses no arrays whatsoever.

#include <stdio.h>

int main() {
    int k, t, N, B, max, num_tests;
    scanf("%d", &num_tests);
    while (num_tests--) {
        scanf("%d %d", &N, &B);
        for (k=N/B,max=0; k>0; k--) {
            t = (N-k*B) * k;
            if (t > max) max = t;
        }
        printf("%d\n", max);
    }
    return 0;
}

这篇关于如何存储多达1,000,000,000个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆