WSQ06 “Factorial Calculator”

--Originally published at blog de Horacio

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).

progress:

primero tenemos que definir las variables de tipo int.

después tenemos que hacer un ciclo en el cual el numero factorial salga.

El factorial de un entero positivo n, el factorial de n o n factorial se define en principio como el producto de todos los números enteros positivos desde 1 (es decir, los números naturales) hasta n. Por ejemplo,

5!=1×2×3×4×5=120. 

La operación de factorial aparece en muchas áreas de las matemáticas, particularmente en combinatoria y análisis matemático. De manera fundamental el factorial de n representa el número de formas distintas de ordenar n objetos distintos (elementos sin repetición). Este hecho ha sido conocido desde hace varios siglos, en el siglo XII por los estudiosos hindúes.

La definición de la función factorial también se puede extender a números no naturales manteniendo sus propiedades fundamentales, pero se requieren matemáticas avanzadas, particularmente del análisis matemático.

La notación matemática actual n! fue usada por primera vez en 18081 por Christian Kramp (1760–1826), un matemático francés que trabajó en especial sobre los factoriales toda su vida.

Github source:

 

 


Foctorial numbers

--Originally published at Solving problems with programming

This homework was a little bit more dificult for me at the biggining, i didn’t understand what was a recursion and how did they work. I wrote it just because a web page said how, but I didn’t understand how it worked. After analizing it finally i understood .

A recursion is the call of the same function that is being defined at that moment. You can define a function and at the same time use it inside that function. It is confusing to understand and to explain also hahaha, but in the code and by doing the exercise you could understarnd it.

int factorial(int n){
int resultado;
if(n>0)
resultado=n*factorial(n-1);
else if(n==0)
resultado=1;
return resultado;

I will simulate an exucution of this function. If n=2, n is bigger than 0 so, we will multiply n by the factorial of n-1 that equals 1. So the factorial of 1 is  1 multiply by the factorial of 1-1 that equals 0. So the factorial of 0 is 1, because that is said on the function, if(n==0) resultado=1. So 2*1*1 gives 2.

Here is all the code

#include <iostream>
using namespace std;
int factorial(int n){
int resultado;
if(n>0)
resultado=n*factorial(n-1);
else if(n==0)
resultado=1;
return resultado;
}
main(){
int num, res;
char op;
do{
cout<<“Escribe el número que desea convertir en factorial”<<endl;
cin>>num;
res = factorial(num);
if(res==0)
cout<<“No se puede sacar el factorial a numeros negativos “<<endl;
else{
cout<< “El número factorial es “<<res<<endl;
}
cout<<“¿Quieres calcular otro número factorial?(S/N)”;
cin>>op;
if(op==’N’||op==’n’)
cout<<“Ten un lindo día”<<endl;
}while(op==’S’||op==’s’);
return 0;
}

I also solve the factorial number with loops do while and for, that are easier to make. The code is linked if you like to take a look.


Factorial calculator… #WSQ06

--Originally published at It&#039;s me

New WSQ! In this activity we had to create a program that given a non-negative integer number, the program displays the factorial number (n!). Also, keep asking the user if they would like to try another number until their anwer is no (n). The first part was a difficult, I researched and found this program, which helped me to do mine, I did it a little different but it helped me a lot. The part of asking a user was easy, I love loops with do while. Here is my code running: WSQ06..WSQ06

Original header image recovered from: https://www.flickr.com/photos/sebadorn/3707431457/in/photolist-6DByd2-biaDRz-4kG6hW-9Ajs9g-BoSK4-7vBn3V-bgfAgD-biaK7a-4rRFMF-dDxUf7-79pk6F-2SWDrK-t63a9-kjthw-73syCt-5x1Ufz-6uxER-cufGLJ-ozqGP9-dRDxgX-CzRu4-82Fz87-5XetFa-9gEPb-9DYpP-82Fz7W-9uYQH-uDun-7b4ZcZ-6DtkQL-9hi6k1-3j7ciB-3j7qrv-3jbLqo-3jbFGS-7ypyhq-4rVKab-3jbJ1Y-3jbw2q-6WNg3f-8TCx8q-8iUqcs-3hoNfA-ksG9f-bay68D-3jbK8j-6pFNS-3jbGUN-UmZfT-SH5TPN


WSQ06.Factorial-lml.

--Originally published at Programming Path

More loops!! Haha I actually forgot how to do some loops, but thanks to Sergio, I could remember that exist the loop of DO.

The assignment  was to ask the user a non-negative number to find its factorial number. It doesn’t specify if it has to be done as a function or not, but I decided to do it as a function.

Here is the code:

wsq06

It wasn’t that hard, but like I said before, I forgot that I could do a loop with DO.

Thanks for reading.


#WSQ06

--Originally published at OlafGC / Class #TC1017

Long time no see you, guys. This is a blog post for the WSQ06, which is a factorial calculator. The tricky part is to write down the function, to understand the logic of the factorial numbers to teach it to the computer. I used a float because when you get the factorial of a big number things get pretty nasty for an int. And in the end, you just need to write a loop in case the user wants to run the program again (which we’ve already done dozens of times).

Code:

#include <iostream>
using namespace std;
float factorial(float n)
{
float result;
if(n>0)
result=n*factorial(n-1);
else if(n==0)
result=1;
return result;
}
main ()
{
float num, res;
char op;
do{
cout<<“Write the number you want to convert:”<<endl;
cin>>num;
res = factorial(num);
if(res==0)
cout<<“You cannot get factorials from negative numbers.”<<endl;
else{
cout<<“The factorial number is: “<<res<<“.”<<endl;
}
cout<<“Do you want to calculate another number? (y/n) “;
cin>>op;
if(op==’N’||op==’n’)
cout<<“Have a nice day!”<<endl;
else
cout<<“Let’s go again!”<<endl;
}
while(op==’Y’||op==’y’);
return 0;
}

 


Calculo Factorial ??? …WSQ06

--Originally published at Hensel

Este programa sirve para calcular el numero factorial. Pero que es esto, pues Disfruta las Matemáticas explica que el numero factorial no es mas que el calculo de un numero que se multiplica por su antecesor y el resultado se multiplica por el numero anterior y así sucesivamente hasta llegar al numero 1. Por ejemplo, si queremos calcular el numero factorial del numero 5, la operación sera la siguiente 5*4*3*2*1=120 (2011).

Consecuentemente, una vez aprendido que es el numero factorial pude desarrollar el programa de la siguiente manera.

wsq06

Al comenzar a escribir el código, declare algunas de mis variables en variables tipo “int”, más adelante explicare porque después las declare en tipo “int64_t”. Por ahora comenzare con el desarrollo del programa, en primera estancia empece con un “do-While” y lo que hace es básicamente repetir el código mientras la variable “answer” que es de tipo “string”(osea que en este tipo de variable podemos guardar palabras) sea answer==’yes’|| answer==’YES’|| answer==’Yes’. Pero porque comparamos tres veces la variable “answer”, la razón es porque el usuario pudo haber ingresado la palabra yes con mayúsculas, minúsculas o con la primer letra en mayúscula y de no haber aumentado el margen de comparación probablemente el programa lo tomara como una respuesta negativa. Siguiendo la imagen del código, podemos observar que se despliega un mensaje para que el usuario ingrese el numero del que se quiere calcular su factorial, después se habre otro “do-While” el cual repetira la siguiente ecuación “num=num*cont” hasta obtener el resultado deseado usando un “for” para poder decrementar a la variable “cont” que es la que se multiplica por el numero ingresado y despues el resultado se multiplica por el “cont” decrementado nuevamente y así hasta que “cont” sea igual a 1.

Porque utilice el tipo “int64_t”, la razón es por el

wsq06prueba
Continue reading "Calculo Factorial ??? …WSQ06"

WSQ – 06, Factorial calculator

--Originally published at The Clueless Programmer

So what this wsq asked us, was to do a program that got the factorial of a number, which to people that don´t know (like me before I looked it up on Wikipedia) is the product of all the numbers that precede a number. Example, the factorial of 4 is 24 (4*3*2*1). And then it asked us to continually asked the user if he wanted to get the factorial of another number until he said no. When I first got into this assignment I didn´t know what to do or where to start because I hadn´t understood the whole concept yet, but I got some help from this webpage and from the blogpost of one of my classmates, and then I knew what to do.

So here´s the program:

imagen1

So as you can see first I name the variables and explain the program and then I start the recursion function, I started it after I introduced the program because I don´t want that to keep popping of over and over. Then I set my control variable to 1, it is important to do it here so that the value resets everytime the program starts again.

After this I create an “if” in which, if the value is negative or zero, the program says that has no factorial and sets the repetitive contition to “y”, so the program starts over. Then I start another loop that multiplies a variable equaled to the number with the variable equaled to one, later substracting one from the first variable while this is bigger than than one.

The program is basically over at this point, the only thing left would be to print the value to the user and then ask him if he wants to do it again. The answer to this question

Continue reading "WSQ – 06, Factorial calculator"

Factorial Calculator

--Originally published at my programming blog

This week I needed to do the assignment WSQ06, where I needed to aske the user for a number and calculate its factorial, also the number couldn’t be negative and I needed to ask the user if he wanted to try again or no.

So what I did was:

  1. I named my variables, an integer “x”, a string ans, and a long “factorial” (which is like an int but it has space for more numbers)
  2. I made a do while loop which makes all the request and at the end if the condition of the while is true then it repeats.
  3. Inside the do while loop I asked the user for a number and if the number was negative I did an if so that the user could enter a positive number and then I used an else where if the number was positive the program calculated the factorial.
  4. The factorial was calculated by a for loop, I names int i=1 and the if i was smaller or equal to the number the user had entered each time this loop would repeat itself.
  5. Inside the for loop I equaled the long factorial to factorial*i so that each time the loop repeats the factorial multiplies bye the value of i (that increases each time) until i is equal to the number entered.
  6. Then I printed the result of the factorial and asked the user if he wanted to try again.
  7. if the user entered y for YES the program would repeat, but if the user entered n the program would stop and print “Okay thank you and have a good day!”.
  8. This was done with while of the do while loop, the condition of the while was that while the character ans was not equal to n then the program
    screen-shot-2017-02-22-at-12-45-16-pm
    screen-shot-2017-02-22-at-2-47-38-pm
    Continue reading "Factorial Calculator"