Dados dos números positivos y distintos, la tarea es encontrar el mayor de dos números dados sin utilizar declaraciones condicionales (si…) ni operadores (?: en C/C++/Java).
Ejemplos:
Input: a = 14, b = 15 Output: 15 Input: a = 1233133, b = 124 Output: 1233133
El enfoque es devolver el valor sobre la base de la siguiente expresión:
a * (bool)(a / b) + b * (bool)(b / a)
La expresión a / b dará 1 si a > b y 0 si a < b (solo después de encasillar el resultado en bool).
Por lo tanto, la respuesta será de la forma a + 0 o 0 + b dependiendo de cuál sea mayor.
C++
// C++ program for above implementation #include <iostream> using namespace std; // Function to find the largest number int largestNum(int a, int b) { return a * (bool)(a / b) + b * (bool)(b / a); } // Drivers code int main() { int a = 22, b = 1231; cout << largestNum(a, b); return 0; }
Java
// Java program for above implementation class GFG { // Function to find the largest number static int largestNum(int a, int b) { return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0); } // Drivers code public static void main(String[] args) { int a = 22, b = 1231; System.out.print(largestNum(a, b)); } } // This code is contributed by 29AjayKumar
Python3
# Function to find the largest number def largestNum(a, b): return a * (bool)(a // b) + \ b * (bool)(b // a); # Driver Code a = 22; b = 1231; print(largestNum(a, b)); # This code is contributed by Rajput-Ji
C#
// C# program for above implementation using System; class GFG { // Function to find the largest number static int largestNum(int a, int b) { return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0); } // Driver code public static void Main(String[] args) { int a = 22, b = 1231; Console.Write(largestNum(a, b)); } } // This code is contributed by Rajput-Ji
PHP
<?php // PHP program for above implementation // Function to find the largest number function largestNum($a, $b) { return ($a * (boolean)floor(($a / $b))) + ($b * (boolean)floor(($b / $a))); } // Drivers code $a = 22; $b = 1231; echo(largestNum($a, $b)); // This code is contributed // by Mukul Singh
Javascript
<script> // Javascript program for above implementation // Function to find the largest number function largestNum(a , b) { return a * (parseInt(a / b) > 0 ? 1 : 0) + b * (parseInt(b / a) > 0 ? 1 : 0); } // Driver code var a = 22, b = 1231; document.write(largestNum(a, b)); // This code is contributed by shikhasingrajput </script>
Producción:
1231
Publicación traducida automáticamente
Artículo escrito por Ujjwal Aryal y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA