查找产品 Hackerearth

问题描述 投票:0回答:2

我为 hackerearth 上的 findproduct 编写了这段代码。当我编译和测试时,它没有显示任何错误,但是当我提交代码时,它显示错误的答案。有人可以帮我吗。

问题链接: https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-product/description/

#include<iostream>     
using namespace std;

int main()

{        
        int n,p=1;    
        cin>>n;     
        int a[n];

        for(int i=0;i<n;i++)
        {       
            cin>>a[i];        
    
            p=(p*a[i])%1000000007;

        }          
        cout<<p;           
        return 0;     
}
c++ arrays
2个回答
0
投票

您使用了错误的数据类型。你会得到溢出。您可以获得的最大数字是 1000000007 * 1000000007。这不适合整数,将导致 -371520463。

(其实最大的数字是1000000006)

请将您的数据类型更改为 unsigned long long。

您的声明

int a[n];
不符合C++标准。它偶然与你的编译器一起工作。但它不是 C++。

您也根本不需要数组。读完后可以直接相乘。

这样您可以节省大量内存。

众多可能的解决方案之一:

#include <iostream>

constexpr unsigned long long primeModulo = 1000000007ULL;

int main() {
    
    // Here we will store the result 
    unsigned long long product{ 1 };

    // Read number of values to multiply
    if (size_t numberOfValues{}; std::cin >> numberOfValues)

        // Now, read numberOfValues and multiply them with modulo
        for (size_t i{}; i < numberOfValues; ++i)

            // Read value
            if (unsigned long long value{}; std::cin >> value)

                // Perform multiplication
                product = (product * value) % primeModulo;

    // Show result to user
    std::cout << product;
    return 0;
}

模运算规则

1. ( a + b ) % c = ( ( a % c ) + ( b % c ) ) % c
2. ( a * b ) % c = ( ( a % c ) * ( b % c ) ) % c
3. ( a – b ) % c = ( ( a % c ) - ( b % c ) ) % c (caveat with negative values!)
4. ( a / b ) % c  NOT EQUAL TO ( ( a % c ) / ( b % c ) ) % c

0
投票

您需要将product变量作为long long int。另外,您不需要在这里创建数组。

#include <iostream>
using namespace std;

int main(){
    
    int n,a;
    cin >> n;
    long long int p=1;
    
    for(int i=0; i<n; i++){
         cin >> a;
         p = (p*a)%1000000007;
    }
    cout << p;
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.