Home >Backend Development >C++ >Why is my program failing to find prime numbers within a long variable, and how can I fix it?

Why is my program failing to find prime numbers within a long variable, and how can I fix it?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-13 22:01:46910browse

Why is my program failing to find prime numbers within a long variable, and how can I fix it?

Troubleshooting Prime Number Identification in Long Variables

A user reported problems getting output when trying to identify prime numbers within a long variable. The original program contained a flaw preventing correct results.

Problem Analysis

The primary error stemmed from incorrect loop variable initialization. The outer loop's condition (i <= num) was inefficient and likely caused the program to run indefinitely or produce incorrect results.

Enhanced Code

Below is a revised program that resolves these issues and efficiently finds prime numbers within a given range:

<code class="language-csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PrimeNumberFinder
{
    class Program
    {
        static void FindPrimes(long num)
        {
            bool isPrime;
            for (long i = 2; i <= num; i++)
            {
                isPrime = true;
                for (long j = 2; j * j <= i; j++)
                {
                    if (i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    Console.WriteLine(i);
                }
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number:");
            long inputNum;
            if (long.TryParse(Console.ReadLine(), out inputNum))
            {
                FindPrimes(inputNum);
            }
            else
            {
                Console.WriteLine("Invalid input. Please enter a valid long integer.");
            }
        }
    }
}</code>

Performance Enhancements

This improved code offers better performance, approaching O(n log log n) time complexity, making it suitable for larger ranges of numbers. The inner loop condition (j * j <= i) is a key optimization.

The above is the detailed content of Why is my program failing to find prime numbers within a long variable, and how can I fix it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn