Você está na página 1de 16

TECNOLOGICO NACIONAL DE MEXICO

INSTITUTO TECNOLÓGICO DE TEPIC


ING. S IS TEMAS COMPUTACIONALES
INTEGRANTES :
BRAYAN ADAN GUTIERREZ RODRIGUEZ
CRIS TOFER DAVID CANALES ALMENDARES
LUIS MIGUEL HERNANDEZ MACIAS

ESTRUCUTRA DE DATOS
AED-1026
11:00 – 12:00 AM LCSB
UNIDAD 2
PROYECTO
FECHA DE ENTREGA:
17 DE SEPTIEMBRE 2018

MTRO. JUAN RAUL ARCADIA PEÑA


FUNCIONES RECURSIVAS
Y
CÍCLICAS
Contenido
PRÓLOGO..................................................................................................................................... 4
INTRODUCCIÓN:........................................................................................................................... 4
FACTORIAL HASTA N ..................................................................................................................... 5
POTENCIA RECIVE LA PONTENCIA Y EL NÚMERO ............................................................................ 5
POTENCIA DE 2 ............................................................................................................................. 6
SUMA EN CADENA ........................................................................................................................ 6
SUMA DE 1 A N............................................................................................................................. 7
SUMA HASTA N ............................................................................................................................ 7
INVENTIR NÚMERO ...................................................................................................................... 7
DIVISIÓN ...................................................................................................................................... 8
ES PALINDROMO .......................................................................................................................... 8
MINIMO COMUN DIVISOR............................................................................................................. 9
SUMA DE MULTIPLOS DE N ........................................................................................................... 9
FUNCIÓN QUE SUMA DEL RANGO A-B ......................................................................................... 10
SUMA DE TODOS LOS ELEMENTOS DE UN VECTOR ....................................................................... 10
MULTIPLICACION RUSA............................................................................................................... 11
FUNCIÓN QUE SUMA LOS DIVISORES DE 5 ................................................................................... 11
FUNCIÓN QUE VERIFICA SI ES PRIMO ........................................................................................... 12
FUNCIÓN QUE VERIFICA SI ES NUMERO PERFECTO ....................................................................... 12
FUNCIÓN QUE VERIFICA SI ES POSITIVO ....................................................................................... 13
FUNCIÓN QUE SUMA ELEMENTOS PARES DE UN ARRAY ............................................................... 13
ARREGLO DE UNA DIMENSION QUE RETORNE EL MAYOR ............................................................. 14
FUNCIÓN QUE VERIFICA SI ES PAR ............................................................................................... 14
SUMA LA DIAGONAL PRINCIPAL .................................................................................................. 15
SUMA TODOS LOS ELEMENTOS DEL ARRAY .................................................................................. 15
FUNCIÓN QUE INVIETE STRING.................................................................................................... 16
FUNCIÓN QUE CUENTA PRIMOS .................................................................................................. 16
PRÓLOGO
El manual de Ejercicios de Programación en Java: Recursividad nace después de conocer la unidad 2
de la materia Estructura de datos: Con el paso del tiempo hemos constatado que aprender un lenguaje
de programación es relativamente sencillo y sobre este tema existe mucho y muy buen contenido, pero
aprender a programar es algo totalmente distinto, que necesita de un mayor esfuerzo y abordar el
problema desde otra perspectiva.

INTRODUCCIÓN:
Este documento está compuesto por un conjunto de funciones las cuales fueron creadas a lo largo de
esta unidad, cada uno de estos no tienen solución única, aquí se plantea la más didáctica y fácil de
entender en su forma recursiva y utilizando un ciclo, dejando un poco de lado la eficiencia.

Existen distintas soluciones, para cada uno de los ejercicios, especialmente en este contenido estamos
utilizando dos versiones diferentes por cada ejercicio, se incluye más de una solución por el método
recursivo y otro utilizando ciclos. La resolución de los ejercicios de programación en forma recursiva
tendrá como objetivo utilizar esta técnica, con esto poder realizar una llamada a una función un número
de veces que nosotros deseemos (n), desde ella misma, de allí su nombre. Y en la otra opción que se
desarrollara, será utilizando las funciones con ciclos como lo son: while, do while y el ciclo for.
RECURCIVIDAD
CICLOS

UN EJEMPLO DE COMO SE DIVIDEN TODOS LOS PROGRAMAS


TITULO DE FUNCIÓN
Public static void Ejemplo (int a, int b){
CODIGO DE LA FUNCIÓN ANÁLISIS DEL ALGORITMO
Int r=0; // 1
For(int i=0;i<a;i++){ // 1+n+1+n
r=a+b; // 2n
} //
RESULTADO DEL ALGORITMO
} // 4n+2

FACTORIAL HASTA N
Esta función retorna el número factorial que le introduzcan.

public static int FactorialRecurcividad(int n) {


if (n == 1) { // n
return 1; //
} else { //
return n * FactorialRecurcividad(n - 1); // 3
} //
} // n+3
public static int Factorial(int n) {
int f = 1; //1
for (int i = 1; i <= n; i++) { //1+n+1+n
f = f * i; //1+1
} //
return f; //1
} // 4n+4

POTENCIA RECIVE LA PONTENCIA Y EL NÚMERO


Esta función eleva a la potencia indicada el número que se especifique.

public static int pontN(int x,int n){


if(n==0){ // n+1
return 1; //
}else return x*pontN(x,n-1); // 2
} // n+3
public static int Potencia(int x, int n) {
int f = 0; //1
for (int i = 1; i <= n; i++) { //2n+2
f = f + (x * x); //3n
} //
return f; //1
} // 5n+4
POTENCIA DE 2
Esta función eleva el número 2 a la potencia indicada.

public static int potencia2nMejorado(int n) {


if (n == 0) { // n+1
return 1; //
} else if (n == 1) { // n
return 2; //
} //
return 2 * potencia2nMejorado(n-1); // 3
} // 2n+4
public static int dosAlan(int n){
int r=0; // 1
for(int i=1;i<n;i++){ // 2n+2
r=r+(2*2); // 3n
} //
return r; // 1
} // 5n+4

SUMA EN CADENA
Esta función suma los dígitos de un número.

public static int sumaCadena(int n) {


if (n < 10) { // n
return n; //
} else { //
return n % 10 + sumaCadena(n / 10); // 4
} //
} // n+4
public static int sumaCadena(int n){
int aux,total=0; // 2
aux=n; // 1
while(n != 0){ // n
total+=n%10; // 2
n=n/10; // 2
} //
return total; // 1
} // 5n+4
SUMA DE 1 A N
Esta función suma los números de 1 hasta n utilizando la sumatoria de Riemann.

public static int SumaRiemann(int n) {


return (n * (n + 1) / 2); // 3
} // 3
public static int de1AN(int n){
int r=0; // 1
for(int i=0;i<=n;i++){ // 2n+2
r+=i; // n
} //
return r; // 1
} // 3n+4

SUMA HASTA N
Esta función suma los números de 1 hasta n.

public static int sumalaNR(int n) {


if (n == 1) { // n
return n; //
} else { //
return n + sumalaNR(n - 1); // 3
} //
} // n+3
public static int sumalaN(int n) {
int r = 0; //1
for (int i = 1; i <= n; i++) { //2n+2
r = r + i; //2n
} //
return r; //1
} // 4n+4

INVENTIR NÚMERO
Esta función invierte un número.

public static int InvertirFunciona(int n) {


int p = (n + "").length() - 1; // 3
if (n < 10) { // n
return n; //
} else { //
return (n % 10) * (int) Math.pow(10, p) + (InvertirFunciona(n / 10)); // 5
} //
} // n+8
public static int invertirNumero(int n){
int cifra, inverso = 0; // 2
while(n!=0){ // n
cifra = n%10; // 2n
inverso = (inverso * 10) + cifra; // 3n
n/=10; // 1n
} //
return inverso; // 1
} // 7n+3
DIVISIÓN
Esta función divide un número entre otro.

public static int division(int a, int b) {


if (a < b) { // n
return 0; //
} else { //
return 1 + division(a - b, b); // 3
} //
} // n+3
public static int divisionRestas(int a, int b){
int c=0; // 1
a=a-b; // 2
while(a >= 0){ // n
c=c+1; // 2n
a=a-b; // 2n
} //
return c; // 1
} // 5n+4

ES PALINDROMO
Esta función verifica si la palabra es palíndromo o no.
public static boolean espalindromo(String cad) {
cad = cad.replace("", ""); // 2
cad = cad.toLowerCase(); // 2
if (cad.length() <= 1) { // 2n
return true; //
} else if (cad.charAt(0) != cad.charAt(cad.length() - 1)) { // 4n
Return false; //
} else { //
return espalindromo(cad.substring(1, cad.length() - 1)); //
} // 3
} // 6n+7
public static boolean palindromoCiclo(String n){
String n1=""; // 1
for (int i = n.length() - 1; i >= 0; i--) { // 2n
n1 = n1 + n.charAt(i); // 3n
} if(n.equals(n1)){ // 1
return true; //
}else return false; // 1
} // 5n+3
MINIMO COMUN DIVISOR
Esta función específica el mínimo común divisor.

public static int mcd(int a, int b) {


if (b == 0) { // n
return a; //
} else { //
return mcd(b, a % b); // 2
} //
} // n+1
public static int mcd(int n1, int n2) {
int mcd = 0; // 1
int a = Math.max(n1, n2); // 2
int b = Math.min(n1, n2); // 2
do { //
mcd = b; // 1n
b = a % b; // 2n
a = mcd; // 2n
} while (b != 0); // n
return mcd; // 1
} // 6n+6

SUMA DE MULTIPLOS DE N
Esta función suma los múltiplos de n.

public static int sumademultipliosden(int n) {


if (n < 5) { // n
return 0; //
} else if (n % 5 == 0) { // 2n
return n + sumademultipliosden(n - 1); // 3
} else { //
return sumademultipliosden(n - 1); //
} //
} // 3n+3
public static String multiplosN(int n, int cantidad){
String cad=""; // 1
for(int i=n; i<=(n*cantidad); i+=n) // 3n+3
cad+=i+","; // 2n
return cad; // 1
} // 5n+5
FUNCIÓN QUE SUMA DEL RANGO A-B
Esta función suma todos los números del rango A hasta B.

public static int sumatoriadelrangodeaab(int a, int b) {


if (a > b) { // n
return sumatoriadelrangodeaab(b, a); //
} else if (a == b) { // n
return a; //
} else { //
return b + sumatoriadelrangodeaab(a, b - 1); // 3
} //
} // 2n+3
public static int sumaRango(int a, int b){
int suma=0; // 1
for(int i=a; i<b; i++) // 2n+2
suma+=i; // n
return suma; // 1
} // 3n+4

SUMA DE TODOS LOS ELEMENTOS DE UN VECTOR


Esta función suma todos los elementos de un vector

public static int Sumadevector1(int A[], int i) {


if (i == 0) { // n+1
return 0; //
} else { //
return A[i - 1] + Sumadevector1(A, i - 1); // 4
} //
} // n+5
public static int sumaVector(int A[]){
int suma=0; // 1
for(int i=0; i<A.length; i++) // 2n+2
suma+=A[i]; // n
return suma; // 1
} // 3n+4
MULTIPLICACION RUSA

Esta función utiliza la multiplicación rusa.


public static int multiplicacionrusa(int a, int b) {
if (a == 1) { // 2^n
return b; //
} else if (a % 2 != 0) { // n
return b + multiplicacionrusa(a / 2, b * 2); // 4
} else { //
return multiplicacionrusa(a / 2, b * 2); //
} //
} // log
public static int multiplicacionRusaciclos(int a, int b){
int c=0; // 1
while(a!=0){ // 2^n
if(a % 2 != 0){ // 2
c = c + b; // 2
} //
a = a / 2; // 2
b = b * 2; // 2
} //
return c; // 1
} // log

FUNCIÓN QUE SUMA LOS DIVISORES DE 5

Esta función suma los múltiplos de 5 en un número.

Public static int sumaDiv5(int n){


If(n<5){ // n
return 0; //
}else if(n%5==0){ // 2n
return n+sumaDiv5(n-1); // 3
} else return sumaDiv5(n-1); //
} // 3n+3
public static int sumaDiv5(int n){
int r=0; // 1
for(int i=0;i<=n;i++){ // 2n+2
if(i%5==0){r+=i;} // 2n
} //
return r; // 1
} // 4n+4
FUNCIÓN QUE VERIFICA SI ES PRIMO
Esta función verifica si un número es primo o no.

public static boolean primos(int p) {


if (p == 2 || p == 1) { // 3
return true; //
} else { //
return primos(p, p / 2); // 2
} //
} // 5
public static boolean primos(int p, int n) {
if (n == 1) { // n
return true; //
} else if (p % n == 0) { // n
return false; //
} //
return primos(p, n - 1); // 2
} // 2n+2
public static boolean primos(int n){
int r=0; // 1
for(int i=1;i<=n;i++){ // 2n+2
if(n%i==0){ // n
r++; // n
} //
} //
return r==2; // 1
} // 4n+4

FUNCIÓN QUE VERIFICA SI ES NUMERO PERFECTO


Esta función verifica si un número es perfecto o no.
public static boolean numeroPerfecto(int n, int d, int s) {
if (d == 0) { // n
return s == n; //
} else if (n % d == 0) { // n
return numeroPerfecto(n, d - 1, s += d); // 3
} else { //
return numeroPerfecto(n, d - 1, s); //
} //
} // 2n+3
public static boolean numeroPerfecto(int n){
int suma=0; // 1
for(int i=1; i<n; i++){ // 2n+2
if(n%i==0){ // 2n
suma=suma+i; // 2n
} //
} //
if(suma==n){ // 1
return true; //
}else return false; // 1
} // 6n+5
FUNCIÓN QUE VERIFICA SI ES POSITIVO
Esta función verifica si es número positivo o no.

public static boolean positivo(int n) {


if (n > 0) { // 1
return true; //
} else { //
return negativo(n); // 1
} //
} // 2
public static boolean negativo(int n) {
if (n < 0) { // 1
return false; //
} else { //
return positivo(n); // 1
} //
} // 2
public static boolean positivo(int n){
return n>0; // 1
} // 1

FUNCIÓN QUE SUMA ELEMENTOS PARES DE UN ARRAY


Esta función suma todos los elementos pares de un arreglo de una dimensión.

public static int regresasumapar(int C[], int r, int suma) {


if (r == 0) { // n
return suma; //
} //
if (C[r] % 2 == 0) { // n
suma += C[r]; // 1
return regresasumapar(C, r - 1, suma); // 2
} //
return regresasumapar(C, r - 1, suma); //
} // 2n+3
public static int sumaPar1D(int A[]){
int r=0; // 1
for(int i=0;i<A.length;i++){ // 2n+2
if(A[i]%2==0){ // n
r+=A[i]; // n
} //
} //
return r; // 1
} // 4n+3
ARREGLO DE UNA DIMENSION QUE RETORNE EL MAYOR
Esta función retorna el número mayor de un arreglo de una dimensión.

public static int retornamayorrec(int C[], int r, int m) {


if (r == 0) { // n
return m; //
} //
if (C[r] > m) { // n
m = C[r]; // n
return retornamayorrec(C, r - 1, m); // 2n
} //
return retornamayorrec(C, r - 1, m); //
} // 5n
public static int mayorA1D(int A[]){
int m=A[0]; // 1
for(int i=1;i<A.length;i++){ // 2n+2
if(A[i]>m){ // n
m=A[i]; // n
} //
} //
return m; // 1
} // 4n+3

FUNCIÓN QUE VERIFICA SI ES PAR


Esta función verifica si un número es par o no.

public static boolean numpar(int n) {


if (Math.abs(n) % 2 == 0) { // 3
return true; //
} else { //
return numimpar(n); // 1
} //
} // 4
public static boolean numimpar(int n) {
if (Math.abs(n) % 2 != 0) { // 3
return false; //
} else { //
return numpar(n); // 1
} //
} // 4
public static boolean par(int n){
return Math.abs(n)%2==0; // 3
} // 3
SUMA LA DIAGONAL PRINCIPAL
Esta función suma la diagonal principal de un arreglo de 2 dimensiones.

public static int sumaArray2D(int A[][]) {


return sumaArray2D(A, A.length - 1); // 2
} // 2
public static int sumaArray2D(int A[][], int i) {
if (i == 0) { // n
return A[0][0]; //
} else { //
return A[i][i] + sumaArray2D(A, i - 1); // 3n
} // 4n
public static int sumaD2D(int A[][]){
int r=0; // 1
for(int i=0;i<A.length;i++){ // 2n+2
r+=A[i][i]; // n
} //
return r; // 1
} // 3n+4

SUMA TODOS LOS ELEMENTOS DEL ARRAY


Esta función suma todos los elementos de un arreglo de 2 dimensiones.

public static int sumtodos2d(int A[][], int n, int c, int s) {


if (n == (A.length - 1) && c == (A[0].length - 1)) { // 5n
return s = s + A[n][c]; //
} else if (c == (A[0].length - 1)) { // 2n^2
return sumtodos2d(A, n + 1, c = 0, s = s + A[n][c]); // 5n
} else { //
return sumtodos2d(A, n, c + 1, s = s + A[n][c]); //
} //
} // 2n^2+10n
public static int sumaT2D(int A[][]){
int r=0; // 1
for(int i=0;i<A.length;i++){ // 2n+2
for(int k=0;k<A[0].length;k++){ // 2n^2+2n
r+=A[i][k]; // n
} //
} //
return r; // 1
} // 2n^2+5n+4
FUNCIÓN QUE INVIETE STRING
Esta función invierte una cadena.

public static String inversopalabra(String a, int longitud) {


if (longitud == 0) { // n
return a.charAt(longitud) + ""; //
} else { //
return a.charAt(longitud) + inversopalabra(a, longitud - 1); // 4n
} //
} // 5n
public static String invPal(String a){
String r=""; // 1
for(int i=0;i<a.length();i++){ // 2n+2
r=a.charAt(i)+r; // 2n
} //
return r; // 1
} // 4n+4

FUNCIÓN QUE CUENTA PRIMOS


Esta función cuenta cuantos primos existen en un arreglo de una dimensión.

public static int cuenPriR(int A[],int n,int r){


if(n==(A.length-1)){ // 2n-2
return r; //
}else if(primos(A[n])){ // n
return cuenPriR(A,n++,r++); // 3
}else return cuenPriR(A,n+1,r); //
} // 3n+1
public static int cuenPri(int A[]){
int r=0; // 1
for(int i=0;i<A.length;i++){ // 2n+2
if(primos(A[i])){ // n
r++; // n
} //
} //
return r; // 1
} // 4n+4

Você também pode gostar