0

I try to store big integer numbers generated by the method(sumOrProduct). The method takes two numbers N and Q, and it returns sum value when Q is 1 or product value when Q is 2. If N is 4 then sum value is 10(4+3+2+1=10) and product value is 24(4!=24). The code is ok for N = <18 but after that it shows wrong product value.

The code is -

import java.util.Scanner;

public class Solution {

    public static void sumOrProduct(int n, int q) {
    
        if(q==1){
            long count=0;
            while(n != 0){
                count = count+n;
                n--;
            }
            System.out.println(count);
        }
        else if(q == 2){
            long count=1;
            while(n != 0){
                count = count*n;
                System.out.println(count);
                n--;
            } 
            System.out.println(count);
        }
    }
    
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        int T = scan.nextInt();
        while(T --> 0){
            int N = scan.nextInt();
            int Q = scan.nextInt();
            sumOrProduct(N, Q);
        }
        scan.close();
    }
}
Slaw
  • 37,820
  • 8
  • 53
  • 80
  • 2
    Yes try using BigInteger – Scary Wombat Aug 26 '22 at 02:40
  • If you want to return a value from a method you need to change the return type from `void` to what you want `BigInteger` like so `public BigInteger void sumOrProduct(...)` and call the return method `return yourValue;` then store it as a variable, for example `BigInteger result = sumOrProduct(N, Q);` or store it in a list if that is what you want `yourList.add(sumOrProduct(N, Q));` – sorifiend Aug 26 '22 at 02:52

0 Answers0