So I wrote a programm to check if the entered number by user is prime or not. So far it works, but I olso need to change it in order to also print every prime number until the one given by user.
Here is my C# code:
using System;
public class PrimeNumberExample
{
public static void Main(string[] args)
{
int n, i, m = 0, flag = 0;
Console.Write("Prime number finder, enter your number below: ");
n = int.Parse(Console.ReadLine());
m = n / 2;
for (i = 2; i <= m; i++)
{
if (n % i == 0)
{
Console.Write("Is not a prime number.");
flag = 1;
break;
}
}
if (flag == 0)
Console.Write("Is a prime number.");
}
}
Check the code for the comments indicating the start and end of the additional code:
public static void Main(string[] args)
{
int n, i, m = 0, flag = 0;
Console.Write("Prime number finder, enter your number below: ");
n = int.Parse(Console.ReadLine());
m = n / 2;
for (i = 2; i <= m; i++)
{
if (n % i == 0)
{
Console.Write("Is not a prime number.");
flag = 1;
break;
}
//Start added code
bool flagPrime = true;
for (int x = 2; x <= i; x++)
{
if (i % x == 0)
flagPrime = false;
}
if (flagPrime)
Console.WriteLine(i);
//End added code
}
if (flag == 0)
Console.Write("Is a prime number.");
}
Console.Write("Prime number finder, enter your number below: ");
int i, j, n = int.Parse(Console.ReadLine());
bool isPrime = false;
for (i = 2; i <= n; i++)
{
isPrime = true;
for (j = 2; j < (i / 2); j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.WriteLine($"{i} Is a prime number.");
}
}
if (!isPrime)
{
Console.WriteLine($"{n} Is not a prime number.");
}
Find the prime numbers within a range of numbers
public static void Main()
{
int num,i,ctr,stno,enno;
Console.Write("\n\n");
Console.Write("Find the prime numbers within a range of numbers:\n");
Console.Write("---------------------------------------------------");
Console.Write("\n\n");
Console.Write("Input starting number of range: ");
stno = Convert.ToInt32(Console.ReadLine());
Console.Write("Input ending number of range : ");
enno = Convert.ToInt32(Console.ReadLine());
Console.Write("The prime numbers between {0} and {1} are : \n",stno,enno);
for(num = stno;num<=enno;num++)
{
ctr = 0;
for(i=2;i<=num/2;i++)
{
if(num%i==0){
ctr++;
break;
}
}
if(ctr==0 && num!= 1)
Console.Write("{0} ",num);
}
Console.Write("\n");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.