Good day. Carried out the task on http://informatics.msk.ru/ under number 112202. Task:

Write a program that introduces two integers and finds their product without using the multiplication operation. Note that the numbers may be negative.

When checking, 19 out of 24 tests were performed, or 15 and 24. Alas, test conditions are not available to me. Please tell me, how else can you improve the code? Can use BufferedReader ()?

In my code:

import java.util.Scanner; class Series{ static Scanner in = new Scanner(System.in); public static void main (String[] args){ int x = in.nextInt(), a = in.nextInt(), i=0; long c=0; if(a>=0){ while(i!=a){ c+=x; i++;} }else{ while(i!=x&i!=-x){ //при замене "x" на "a" , c+=a; //"a" на "x" тесты показывают 15 из 24 i++;} } System.out.println(c); } } 
  • 2
    your program gives an incorrect result, if both numbers are negative, there may be a problem. In general, make a simple test, loop through all pairs of factors from -10 to 10, and compare the result of your code with the result of multiplication. - zRrr 6:49 pm
  • Forced to disagree with you. I checked before and now I check, everything works. And with and without minuses and with zeros. - Makis
  • Probably I did not take into account that by multiplying "-" by "-" it turns out "+". I apologize for not accuracy. - Makis

1 answer 1

Here is:

 import java.util.Scanner; public class Main { private static long multiply(long a, long b) { if (a == 0 || b == 0) return 0; boolean negative = false; if (a < 0) { negative = true; a = -a; } if (b < 0) { negative = !negative; b = -b; } int result = 0; for (int i = 1; i <= a; ++i) result += b; return negative ? -result : result; } public static void main(final String[] args) { final Scanner scanner = new Scanner(System.in); final long a = scanner.nextInt(); final long b = scanner.nextInt(); System.out.println(multiply(a, b)); } } 
  • But what were the limitations on the tasks? If 10^9 it may not have time ... - pavel
  • Thanks, great solution. The test passed. - Makis