Algorithm

Problem Name: Mathematics - Cutting Paper Squares

In this HackerRank in Mathematics - Cutting Paper Squares solutions,

Mary has an n * m piece of paper that she wants to cut into 1 * 1 pieces according to the following rules:

• She can only cut one piece of paper at a time, meaning she cannot fold the paper or layer already-cut pieces on top of one another.
• Each cut is a straight line from one side of the paper to the other side of the paper. For example, the diagram below depicts the three possible ways to cut a 3 * 2 piece of paper:

Given n and m , find and print the minimum number of cuts Mary must make to cut the paper into n * m squares that are 1 * 1 unit in size.

Input Format

A single line of two space-separated integers denoting the respective values of n and m.

Constraints

• 1 <= n,m <= 109

Output Format

Print a long integer denoting the minimum number of cuts needed to cut the entire paper into 1 * 1 squares.

Sample Input

``````3 1
``````

Sample Output

``````2
``````

Explanation

Mary first cuts the 3 * 1 piece of paper into a 1 * 1 piece and a 2 * 1 piece. She then cuts the 2 * 1 piece into two 1 * 1 pieces:

Because it took her two cuts to get n * m = 3 pieces of size 1 * 1 , we print 2 as our answer.

Code Examples

#1 Code Example with C Programming

```Code - C Programming```

``````
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* ltrim(char*);
char* rtrim(char*);
char** split_string(char*);

int parse_int(char*);

/*
* Complete the 'solve' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
*  1. INTEGER n
*  2. INTEGER m
*/

unsigned long solve(long int n, long int m) {
return (unsigned long)(n*m)-1;
}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

int n = parse_int(*(first_multiple_input + 0));

int m = parse_int(*(first_multiple_input + 1));

long result = solve(n, m);

fprintf(fptr, "%ld\n", result);

fclose(fptr);

return 0;
}

size_t alloc_length = 1024;
size_t data_length = 0;

char* data = malloc(alloc_length);

while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);

if (!line) {
break;
}

data_length += strlen(cursor);

if (data_length  <  alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}

alloc_length <<= 1;

data = realloc(data, alloc_length);

if (!data) {
data = '\0';

break;
}
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';

data = realloc(data, data_length);

if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);

if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}

return data;
}

char* ltrim(char* str) {
if (!str) {
return '\0';
}

if (!*str) {
return str;
}

while (*str != '\0' && isspace(*str)) {
str++;
}

return str;
}

char* rtrim(char* str) {
if (!str) {
return '\0';
}

if (!*str) {
return str;
}

char* end = str + strlen(str) - 1;

while (end >= str && isspace(*end)) {
end--;
}

*(end + 1) = '\0';

return str;
}

char** split_string(char* str) {
char** splits = NULL;
char* token = strtok(str, " ");

int spaces = 0;

while (token) {
splits = realloc(splits, sizeof(char*) * ++spaces);

if (!splits) {
return splits;
}

splits[spaces - 1] = token;

token = strtok(NULL, " ");
}

return splits;
}

int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);

if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}

return value;
}

``````
Copy The Code &

#2 Code Example with C++ Programming

```Code - C++ Programming```

``````
#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector < string> split(const string &);

/*
* Complete the 'solve' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
*  1. INTEGER n
*  2. INTEGER m
*/

long solve(int n, int m) {
return (n*m)-1;
}

int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);

vector < string> first_multiple_input = split(rtrim(first_multiple_input_temp));

int n = stoi(first_multiple_input[0]);

int m = stoi(first_multiple_input[1]);

long result = solve(n, m);

fout << result << "\n";

fout.close();

return 0;
}

string ltrim(const string &str) {
string s(str);

s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun < int, int>(isspace)))
);

return s;
}

string rtrim(const string &str) {
string s(str);

s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun < int, int>(isspace))).base(),
s.end()
);

return s;
}

vector < string> split(const string &str) {
vector<string> tokens;

string::size_type start = 0;
string::size_type end = 0;

while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));

start = end + 1;
}

tokens.push_back(str.substr(start));

}
``````
Copy The Code &

#3 Code Example with C# Programming

```Code - C# Programming```

``````
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Result
{

/*
* Complete the 'solve' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
*  1. INTEGER n
*  2. INTEGER m
*/

public static long solve(int n, int m)
{
return (long)n*(long)m-1;
}

}

class Solution
{
public static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

int n = Convert.ToInt32(firstMultipleInput[0]);

int m = Convert.ToInt32(firstMultipleInput[1]);

long result = Result.solve(n, m);

textWriter.WriteLine(result);

textWriter.Flush();
textWriter.Close();
}
}
``````
Copy The Code &

#4 Code Example with Java Programming

```Code - Java Programming```

``````
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'solve' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
*  1. INTEGER n
*  2. INTEGER m
*/

static long solve(int n, int m) {

return BigInteger.valueOf(n).multiply(BigInteger.valueOf(m)).longValue()-1;
}

}

public class Solution {
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int n = Integer.parseInt(firstMultipleInput[0]);

int m = Integer.parseInt(firstMultipleInput[1]);

long result = Result.solve(n, m);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedWriter.close();
}
}
``````
Copy The Code &

#5 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});

process.stdin.on('end', function() {
inputString = inputString.split('\n');

main();
});

return inputString[currentLine++];
}

/*
* Complete the 'solve' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
*  1. INTEGER n
*  2. INTEGER m
*/

function solve(n, m) {
if (n == 1)
return m-1;
if (m == 1)
return n-1;
return (n-1)*(n*(m-1));
}

function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

const firstMultipleInput = readLine().replace(/\s+\$/g, '').split(' ');

const n = parseInt(firstMultipleInput[0], 10);

const m = parseInt(firstMultipleInput[1], 10);

const result = solve(n, m);

ws.write(result + '\n');

ws.end();
}
``````
Copy The Code &

#6 Code Example with Python Programming

```Code - Python Programming```

``````
#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'solve' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. INTEGER m
#

def solve(n, m):
return (n*m)-1

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

first_multiple_input = input().rstrip().split()

n = int(first_multiple_input[0])

m = int(first_multiple_input[1])

result = solve(n, m)

fptr.write(str(result) + '\n')

fptr.close()

``````
Copy The Code &