Question:

Write a program in C++ to generate and display prime number from 1 to 51.

Show Hint

A key optimization for checking primality is to only test for divisors up to the square root of the number. If a number `n` has a factor larger than its square root, it must also have a corresponding factor smaller than its square root.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Factorial Program in C++

#include <iostream>

int main() {
    int n;
    long long factorial = 1;

    // Prompt user for input
    std::cout << "Enter a positive integer: ";
    std::cin >> n;

    // Check for negative input
    if (n < 0) {
        std::cout << "Factorial is not defined for negative numbers." << std::endl;
    } else {
        // Calculate factorial
        for (int i = 1; i <= n; ++i) {
            factorial *= i;
        }
        std::cout << "Factorial of " << n << " = " << factorial << std::endl;
    }

    return 0;
}

Note:

  • There was a mistake in the original logic: the line factorial = i; was incorrect. It should be factorial *= i; to accumulate the product.
  • Also, the comparison n & Lt; 0 appeared to be a malformed HTML entity — it should be n < 0.
Was this answer helpful?
0
0