WSQ09

Captura de pantalla 2016-04-07 a las 14.17.07
This program will give you the factorial value of a number that you will give.
It’s pretty easy. The function has only int x (which is the number that you’ll give) , and in the function you will have the int n (that will be the factorial number at the end) and int i (that is the actual number in the serie).
The loop will give you the product between n*i, and it will save the product in n, and i will be i + 1 every loop. While i  is lower or equal than x.

It is pretty easy.
Here’s the Code in GitHub.

Factorial calculator WSQ09

Hi everyone! I know that i haven’t blog in a while but I’m back!

What to do?

Create a program that asks the user for a non-negative integer (let’s call that number n) and display for them the value of n! (n factorial). After showing them the answer, ask them if they would like to try another number (with a simple y/n response) and either ask again (for y) or quit the program and wish them a nice day (if they answered n).

Well first of all you need to instal some stuff, the big integer library, at least that was my case, here you have de link for the page BigInteger Library.

Also I recommend you to watch Ken’s video about this, this video is for the last semester, but it might help you.

 

Finally this is my link to my GitHub for my code.

Captura de pantalla 2016-04-07 a las 12.33.01 a.m.

Factorials!

#TC1017 #WSQ09

This programm was very straightforward, since the formula to calculate the factorial is very simple, the tricky part was making the factorial function recursive, because it has to call itself with evey iteration in order to obtain the previous value given to n. In fact, this was my first use of recursion in this semester, that makes it noteworthy I think!

WSQ9

 

 

Source code below: [GitHub link: https://github.com/diegodamy/WSQ09 ]

#include <iostream>
using namespace std;
int factorial (int n){
if (n == 0){
return 1;
} else {
return n*factorial(n-1);
}
}
int main(){
int number;
char decision;

do {
cout << “To calculate the factorial, please enter the integer number:” << endl;
cin >> number;

if (number <0){
cout << “Please enter only positive numbers.” << endl;
cin >> number;
} else {
cout << “The factorial of ” << number << ” is ” << factorial (number) << endl;
}

cout << endl << “Would you like to calculate the factorial of another number? Y/N:” << endl;
cin >> decision;
cout << endl;

} while (decision == ‘Y’);

if (decision !=’Y’){
cout << “Thank you. Goodbye!”;
}

}

————–

Photo Credit: <a href=”https://www.flickr.com/photos/49968232@N00/6267826523/”>Leo Reynolds</a> via <a href=”http://compfight.com”>Compfight</a&gt; <a href=”https://creativecommons.org/licenses/by-nc-sa/2.0/”>cc</a&gt;

WSQ09 – Factorial Calculator

Este programa, como el título lo dice, es una calculadora que realiza factoriales.

logo-factorial

¿Qué es un factorial? Son multiplicaciones de números que van descendiendo a partir de un número dado.

factorial

Gracias a este programa, podemos calcular lo antes dicho.

Se utilizó por primera vez el tipo long que soporta 64 bits, soporta números mas grandes que el int, ¿porqué se utilizó long? Como el programa se trata de realizar factoriales, las multiplicaciones pueden dan como resultado un número demasiado grande que no soportaría el tipo int en dado caso de que el número elegido sea grande.

Se empleó por primera vez en este curso recursividad. Dentro del int main() se utilizó un loop while y un tipo string, este último se utilizó para poder captar una palabra como el “si” cuando te pregunta si quieres volver a intentar a utilizar este programa.

WSQ09 - Factorial Calculator

Link GitHub: WSQ09 – Factorial Calculator

WSQ09 Factorials!

This time we have to do factorials. This means n! = (n)(n-1)(n-2)…(1). Multiply n times the previous number until it reaches 1.

For this I used a for in range (1, x + 1) . When x is the value that the user inputs. The, y = y*i so it keeps repeating itself until it becomes 1. Secondly I used conditionals to predict the parameters when x is 0 or when x is a negative, so the program gives the obvious.

Finally, I took a peek at my classmates’s blog to learn what to do in order to let the user try again or exit the program. Thanks to Pxthon Progrxmmer I learned that you can use a while True to make the whole conditionals and the factorial formula work and when it ends let the user try again by typing ‘a’ or exit by typing a different letter.

wsq009.png

Today’s song is ‘Short Change Hero’ by The Heavy. A song that is used at the intro of Borderlands 2 when introducing the main characters. It is an epic way to show the players what they will meet in the world of Pandora because Pandora “ain’t no place for no hero”.

short change hero

#WSQ09 Factorial Calculator

Para este ejercicio,  lo primero que hice fue hacer un ciclo para que si el usuario ingresa un numero negativo, le vuelva a preguntar y imprima una advertencia de ingresar solo números positivos.

rep=0
r=1
while rep==0:
n= int(input("De que numero quieres saber el factorial: "))
if n<0:
print("por favor, eliga un numero positivo")
rep=0
else:
rep=1

La segunda parte fue hacer otro “while” para que se fueran multiplicando los numero hasta llegar al ingresado por el usuario.

contador=0
while contador<n:
contador=contador+1
r=contador*r
print("El factorial de ",n," es ",r)

Este es el código completo:

rep=0
r=1
while rep==0:
n= int(input("De que numero quieres saber el factorial: "))
if n<0:
print("por favor, eliga un numero positivo")
rep=0
else:
rep=1
contador=0
while contador<n:
contador=contador+1
r=contador*r
print("El factorial de ",n," es ",r)

Para ver el código en Github, click en la imagen:


La compilación:

Facto, facta… ¡Factoriales! #WSQ09

Este código se trata acerca de encontrar el resultado de el factorial de un número. Es decir si introducimos el número 5 y queremos encontrar el resultado de su factorial es: 1 * 2 * 3 * * 5 = 120. Sí lo sé, las matemáticas tienen nombres complicados para cosas sumamente sencillas.

El requerimiento para este código era no usar la función math.factorial(n) porque entonces el código se resumiría a una o 2 líneas así que lo tenemos que hacer de la forma ruda y aquí lo tenemos:

WSQ091

Este código fue hecho bajo un ciclo while.

Mientras que el segundo código lo hicimos así:

WSQ09

Este código fue hecho bajo un ciclo for.

En especial, esta tarea fue muy sencilla de hacer teniendo los conocimientos previos, este código lo había realizado en mi clase de Introducción a la Computación el semestre pasado con la diferencia que lo había realizado en el lenguaje C# y ahí podía usar do/while y eso hacía las cosas mucho más sencillas.

Para hacer una sentencia similar al do/while usé otro ciclo:

while True:
stuff()
if not condition():
break

Este ciclo lo encontré en la página StackOverflow. Tengo que decir que estos chicos si saben de lo que hablan.

A continuación anexo mi código en GitHub como siempre debería haberlo hecho.


# Este código es para encontrar el factorial de un número mediante un while loop.

while True:
    num = int(input("Venga, dame ese número: "))
    res = num - 1
    while res != 1:
        num *= res
        res -= 1
    print("Hola, tu resultado es {}".format(num))
    ques = str(input("¿Quieres intentarlo de nuevo?: "))
    if not ques == "y":
        break

# Este código es para encontrar el factorial de un número mediante un for loop.

while True:
    numb = int(input("Venga, dame ese número: "))
    fact 
Continue reading "Facto, facta… ¡Factoriales! #WSQ09"

#WSQ09

 

For this assignment we needed to make a factorial calculator. The factorial of a number is the multiplication of all numbers that are lesser than that number until 0. For example the factorial of 4 is equal 4x3x2x1=24

This program required loops as we couldnt use the default python function from the math module.

 

-So first I used while loop so the user can use the program as many times he like. 

res=”x”
while (str (res) != “n”):
print (“This program is a factorial calculator”)
n= int (input (“Please give me a positive integer number: “))

 

-Then I implemented a for loop in order to calculate the factorial of any given number. 

for n in range (1,n+1):
num= num*n
print(“The factorial of the given number is: “,num)
print (“”)
print (“y= yes, n= no”)
res=str(input(“You wish to calculate another factorial of a number? “))

 

-And finally I used an If so my loop could work as I wanted.

if (res==”n”):
print(“”)
print(“Have a nice day!”)
else:
print(“”)

 

The final code:

fac

 

The program:

fac2

 

 

 

Btw, I´m not sure if I completely understand how indentation works on python and on my Text editor.