skip to Main Content

(In Dart language) Calculate the factorial value of the number entered as a parameter and return it
Write the method that returns

I’m trying to learn flutter, I’m good at functions, but I couldn’t do it.
What I want is to multiply the entered number backwards. For example, if the entered number is 3, the process will be as follows: 321 will give the answer 6.

2

Answers


  1. First approach (iterative):

    int factorial(int n) {
        if (n < 0) {
          throw ArgumentError('The input number should be a non-negative integer.');
        }
        if (n == 0) return 1;
        int result = 1;
        for (var i = n; i > 0; i--) {
          result *= i;
        }
        return result;
      }
    

    Second approach (recursive):

    int factorialRec(int n) {
        if (n < 0) {
          throw ArgumentError('The input number should be a non-negative integer.');
        }
        if (n == 0 || n == 1) return 1;
        return n * factorial(n - 1);
      }
    
    Login or Signup to reply.
  2. here the method :

    int calculateFactorial(int n) {
      if (n == 0) {
        return 1;
      }
    
      int factorial = 1;
      for (int i = n; i >= 1; i--) {
        factorial *= i;
      }
      return factorial;
    }
    

    here the a full app code :

    import 'package:flutter/material.dart';
    
    int calculateFactorial(int n) {
      if (n == 0) {
        return 1;
      }
    
      int factorial = 1;
      for (int i = n; i >= 1; i--) {
        factorial *= i;
      }
      return factorial;
    }
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatefulWidget {
      const MyApp({super.key});
    
      @override
      State<MyApp> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      final TextEditingController _controller = TextEditingController();
      String result = '';
      String errorText = '';
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Factorial Calculator'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: TextField(
                      controller: _controller,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                        labelText: 'Enter a positive integer',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                        errorText: errorText,
                      ),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      int number = int.tryParse(_controller.text) ?? 0;
                      if (number >= 0) {
                        int factorial = calculateFactorial(number);
                        setState(() {
                          result = 'Factorial of $number is $factorial';
                          errorText = '';
                        });
                      } else {
                        setState(() {
                          result = '';
                          errorText = 'Please enter a positive integer.';
                        });
                      }
                    },
                    child: const Text('Calculate Factorial'),
                  ),
                  if (result.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Text(
                        result,
                        style: const TextStyle(
                          fontSize: 18.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        );
      }
    }
    

    hopefully this will answer your question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search