File tree 2 files changed +71
-10
lines changed
2 files changed +71
-10
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Contribuidores
3
+ - Dromedario de Chapéu
4
+
5
+ Fatorial é uma função matematica que consistem em realizar
6
+ a multiplicação de todos os antecessores de um numero.
7
+
8
+ Ex: 5! = 5 * 4 * 3 * 2 * 1 = 120
9
+ */
10
+
11
+ // A diferença desta implementação para a com recursão é
12
+ // que nesta versão o retorno, é feito utilizado um for
13
+ // que percorre uma lista que vai de 0 a valor + 1
14
+ fn fatorial ( valor : usize ) -> usize {
15
+ let mut total = 1 ;
16
+ // (0..valor + 1) retorna um range, que para ser utlizado é
17
+ // preciso coletar todos os itens dentro de um vetor para assim
18
+ // setr interado, que é isso que .collect::<Vec<usize>>() faz
19
+ for i in ( 0 ..valor + 1 ) . collect :: < Vec < usize > > ( ) . iter ( ) {
20
+ if * i != 0 {
21
+ total *= * i;
22
+ }
23
+ }
24
+ return total
25
+ }
26
+
27
+ fn main ( ) {
28
+ println ! ( "{}" , fatorial( 10 ) ) ;
29
+ }
30
+
31
+ #[ cfg( test) ]
32
+ mod test {
33
+ use super :: * ;
34
+ fn teste_fatorial ( ) {
35
+ assert_eq ! ( fatorial( 0 ) , 1 ) ;
36
+ assert_eq ! ( fatorial( 1 ) , 1 ) ;
37
+ assert_eq ! ( fatorial( 10 ) , 3628800 ) ;
38
+ }
39
+ }
Original file line number Diff line number Diff line change 1
- fn main ( ) {
2
- println ! ( "{:?}" , fatorial_recursiva( 3 ) ) ;
3
- println ! ( "{:?}" , fatorial_recursiva( 4 ) ) ;
4
- println ! ( "{:?}" , fatorial_recursiva( 5 ) ) ;
5
- println ! ( "{:?}" , fatorial_recursiva( 10 ) ) ;
1
+ /*
2
+ Contribuidores
3
+ - Heitor582
4
+ - Dromedario de Chapéu
5
+
6
+ Fatorial é uma função matematica que consistem em realizar
7
+ a multiplicação de todos os antecessores de um numero.
8
+
9
+ Ex: 5! = 5 * 4 * 3 * 2 * 1 = 120
10
+ */
11
+
12
+ // Para realizar uma fatoração com recursão basta fazer o retorno
13
+ // de uma função ser valor * a propia função recebendo valor - 1
14
+ fn fatorial ( valor : usize ) -> usize {
15
+ // Para que não chege a multiplicar por 0 quando chegamos a 1 ou 0
16
+ // é retornado 1 para que o utlimo valor sejá multilpicado por 1
17
+ if valor <= 1 {
18
+ return 1 ;
19
+ }
20
+ return valor * ( fatorial ( valor - 1 ) ) ;
21
+ }
22
+
23
+ fn main ( ) {
24
+ println ! ( "{}" , fatorial( 10 ) ) ;
6
25
}
7
26
8
- fn fatorial_recursiva ( number : i32 ) -> i32 {
9
- if number <= 1 {
10
- return 1 ;
11
- }
12
- number * fatorial_recursiva ( number - 1 )
27
+ #[ cfg( test) ]
28
+ mod test {
29
+ use super :: * ;
30
+ fn teste_fatorial ( ) {
31
+ assert_eq ! ( fatorial( 0 ) , 1 ) ;
32
+ assert_eq ! ( fatorial( 1 ) , 1 ) ;
33
+ assert_eq ! ( fatorial( 10 ) , 3628800 ) ;
34
+ }
13
35
}
You can’t perform that action at this time.
0 commit comments