Asp with C# Prime Number - c#

I'm a 17 year old student currently in software engineering and web development and im having trouble right now with some of my coding. I need to make a project that will alow the user to input a number anywherefrom 0 to 999 and tell whether it is a prime number or not. The code i have so far is....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void primeNumber()
{
int primeNumber1 = int.Parse(Request.Form["Text4"]);
if (primeNumber1 % 1 == 0 & ! (primeNumber1 % 2 == 0 &
primeNumber1 % 3 == 0 &
primeNumber1 % 4 == 0 &
primeNumber1 % 5 == 0 &
primeNumber1 % 6 == 0 &
primeNumber1 % 7 == 0 &
primeNumber1 % 8 == 0 &
primeNumber1 % 9 == 0))
{
Response.Write(" This is a prime number! ");
}
else
{
Response.Write(" This is not a prime Number! ");
}
}
}
... but i cannot get this program to display the correct answer. Any help would be greatly appreciated. Thanks!

You have got the concept of prime numbers wrong. Your code would for example report that 3 is not a prime number, because you check if the number divides evenly in three even if the number entered is three.
The simplest solution would be to loop from 2 and up to primeNumber1 - 1 and check if any of those divides evenly with the number. As you are using a loop, you also need a variable to hold what the result was, as you don't have a single expression that returns the result.
Something like:
bool prime = true;
for (int i = 2; i <= primeNumber1 - 1; i++) {
if (primeNumber1 % i == 0) {
prime = false;
}
}
This is of course the simplest possible solution that solves the problem, for reasonably small numbers. You can for example improve on the solution by exiting out of the loop as soon as you know that it's not a prime number.
You also don't need to loop all the way to primeNumber1 - 1, but only as high as the square root of the number, but you can find out about that if you read up on methods for checking prime numbers.
You need to handle the special cases of 1 and 2 also. By definition 1 is not a prime number, but 2 is.
http://en.wikipedia.org/wiki/Prime_number

bool IsPrime(int number) {
if (number == 1) return false;
if (number == 2) return true;
for (int i = 2; i < number; ++i) {
if (number % i == 0) return false;
}
return true;
}

A little google-fu or a little navel-gazing about prime numbers in general, will lead you to the naive algorithm:
For all n such that 0 < n:
There are two "special case" prime numbers, 1 and 2.
All even numbers > 2 are non-prime, by definition
If you think about the nature of factoring, the largest possible factor you have to consider is the square root of n, since above that point, the factors are reflexive (i.e., the possible factorizations of 100 are 1*100 , 2*50 , 4*25 , 5*20 , 10*10 , 20*5 , 25*4, 50*2 and 100*1 — and the square root of 100 is...10).
That should lead you to an implementation that looks something like this:
static bool IsPrime( int n )
{
if ( n < 1 ) throw new ArgumentOutOfRangeException("n") ;
bool isPrime = true ;
if ( n > 2 )
{
isPrime = ( 0 != n & 0x00000001 ) ; // eliminate all even numbers
if ( isPrime )
{
int limit = (int) Math.Sqrt(n) ;
for ( int i = 3 ; i <= limit && isPrime ; i += 2 )
{
isPrime = ( 0 != n % i ) ;
}
}
}
return isPrime ;
}

Anytime you find yourself in programming repeating a test on a sequential range of numbers you're doing the wrong thing. A better construct for this is a loop. This will give you the range of numbers in an identifier which can then be used to write the repetive code one time. For example I could rewrite this code
primeNumber1 % 2 == 0 &
primeNumber1 % 3 == 0 &
primeNumber1 % 4 == 0 &
primeNumber1 % 5 == 0 &
primeNumber1 % 6 == 0 &
primeNumber1 % 7 == 0 &
primeNumber1 % 8 == 0 &
primeNumber1 % 9 == 0))
As follows
bool anyFactors = false;
for (int i = 2; i <= 9; i++) {
if (primeNumber1 % i != 0) {
anyFactors = true;
break;
}
}
At this point I can now substitute the value allTrue for the original condition you wrote.
if (primeNumber1 % 1 == 0 && !anyFactors)
I can also expand the number of values tested here by substiting a different number for the conditional check of the loop. If I wanted to check 999 values I would instead write
for (int i = 2; i <= 999; i++) {
...
}
Additionally you don't want to use & in this scenario. That is for bit level and operations. You are looking for the logical and operator &&

Try the code below:
bool isPrimeNubmer(int n)
{
if (n >=0 && n < 4) //1, 2, 3 are prime numbers
return true;
else if (n % 2 == 0) //even numbers are not prime numbers
return false;
else
{
int j = 3;
int k = (n + 1) / 2 ;
while (j <= k)
{
if (n % j == 0)
return false;
j = j + 2;
}
return true;
}
}

Related

Check if a number is prime in C# [duplicate]

This question already has answers here:
How does one implement IsPrime() function [duplicate]
(4 answers)
Closed 6 years ago.
the following code works but for some numbers it needs a lot of time to say if the number is prime or not. What can i do to make it faster? Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;``
using System.Text;
using System.Threading.Tasks;
namespace Exercise23
{
class Exercise23
{
static void Main(string[] args)
{
long number = long.Parse(Console.ReadLine());
if (IsPrime(number))
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
}
public static bool IsPrime(long number)
{
if (number == 1) return false;
if (number == 2) return true;
//if (number == 6737626471) return true;
if (number % 2 == 0) return false;
for (int i = 3; i < number; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
}
}
An easiest improvement is to make the loop shorter.
If number is not prime, it can be written as
N = A * B
Let A <= B; in the worst case (A == B) and so A <= sqrt(N).
public static bool IsPrime(long number) {
if (number <= 1)
return false;
else if (number % 2 == 0)
return number == 2;
long N = (long) (Math.Sqrt(number) + 0.5);
for (int i = 3; i <= N; i += 2)
if (number % i == 0)
return false;
return true;
}
So you have O(sqrt(N)) algorithm instead of O(N). For real improvement (for big numbers) see
AKS test (primarily academic use)
https://en.wikipedia.org/wiki/AKS_primality_test
Rabin-Miller test
https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
Based on this answer: https://stackoverflow.com/a/26760082/4499267
a way to speed things up can be:
The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3.
This is because all integers can be expressed as (6k + i) for some integer k and for i = −1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3).
So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1 ≤ √n.
This is 3 times as fast as testing all m up to √n.
Here's a C implementation
int IsPrime(unsigned int number) {
if (number <= 3 && number > 1)
return 1; // as 2 and 3 are prime
else if (number == 1 || number%2==0 || number%3==0)
return 0; // check if number is divisible by 2 or 3
else {
unsigned int i;
for (i=5; i*i<=number; i+=6) {
if (number % i == 0 || number%(i + 2) == 0)
return 0;
}
return 1;
}
}

Find Number of 0's at end of int

I wanted to find out the number of 0's at end of integer.
Suppose anyone enter 2020 it should count 1,if number is 2000 it should show 3 etc;
I tried following but doesn't accomplish what i want :(
Console.WriteLine("Enter Number :");
int num = int.Parse(Console.ReadLine());
int count = 0;
for (int i = 1; i < num.ToString().Count(); i++)
{
//some logic
}
Console.WriteLine("Zero in the tail is :");
Console.WriteLine(count);
You're not changing anything within your loop - so basically, on each iteration it will either increase Count or it won't, and it'll do the same thing each time - so Count will either be the length of the string, or it will be 0.
The simplest option I can think of in terms of text manipulation would be:
string text = num.ToString();
int count = text.Length - text.TrimEnd('0').Length;
Without using text manipulation, however, you could just use division and remainder operations:
int count = 0;
// Keep going while the last digit is 0
while (num > 0 && num % 10 == 0)
{
num = num / 10;
count++;
}
Note that this will yield a count of 0 for the number 0... whereas the first approach will give a count of 1 (because 0.ToString() is "0"). Adjust either piece of code to suit your requirements :)
int GetTrailingZerosFromInteger(int no)
{
if (no == 0)
return 1;
int count = 0;
while(no % 10 == 0)
{
no /= 10;
count++;
}
return count;
}
You can also go the maths way
int n = int.Parse(Console.ReadLine());
int totalzero = 0 ;
while(n > 0){
int digit = n % 10;
if(digit == 0)
totalzero++;
else
break;
n = n / 10;
}
You could do it by just iterating the string from the back something like this:
var strN = 40300.ToString();
int count = 0;
for (var i = strN.Length - 1; strN[i] == '0'; --i, ++count) ;
Console.WriteLine("Result : " + count);
Since a 32-bit integer can have at most nine zeros you can unroll the loop in quite a pleasing way:
int digits =
num == 0 ? 0 :
num % 1000000000 == 0 ? 9 :
num % 100000000 == 0 ? 8 :
num % 10000000 == 0 ? 7 :
num % 1000000 == 0 ? 6 :
num % 100000 == 0 ? 5 :
num % 10000 == 0 ? 4 :
num % 1000 == 0 ? 3 :
num % 100 == 0 ? 2 :
num % 10 == 0 ? 1 : 0;

IS there any way i can make this shorter

I am learning how to use untiy in my spare time by reading a beginners book and looking up stuff online in the book there is a exercise that asks me
to create a script that outputs the numbers from 1 to 10 in to the console but dose not output any multiple of 3 and 5 instead outputting the phrase "programming is awesome "
while i have achieved this task by using this code
using UnityEngine;
using System.Collections;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
for(int i = 1; i <= 10; i++)
{
if(i == 3 )
print ("Programming is Awesome!");
else if (i == 5)
print ("Programming is Awesome!");
else if (i == 6)
print ("Programming is Awesome!");
else if (i == 9)
print ("Programming is Awesome!");
else if (i == 10)
print ("Programming is Awesome!");
else
print (i);
}
}
}
i was wondering if there was any way to achieve the same result only by using less lines of code
You want to use the modulus (aka modulo) operator (%) for this task. It returns the remainder of a division, so when the result of a modulus operation is 0 you know you have a multiple of the divisor.
for (int i = 1; i <= 10; i++)
{
if(i % 3 == 0 || i % 5 == 0)
print("programming is awesome");
else
print(i);
}
for (int i = 1; i <= 10; i++)
{
print((i % 3 == 0 || i % 5 == 0)? "programming is awesome" : i));
}
check out also using ternary operator.
The point of this exercise is that you should calculate the multiples, not just make one condition for every value that you know is a multiple.
Use the modulo operator to check it a number is an even multiple of another. This shows what the modulo operator returns for some values:
i i % 3
------------
1 1
2 2
3 0
4 1
5 2
6 0
7 1
As you see, i % 3 evaluates to 0 when i is a multiple of three. You can use that to check if the number is a multiple of three:
if (i % 3 == 0) {
print ("Programming is Awesome!");
}
Now you should be able to do the same for five also, and incorporate it in your code.
Ways of doing this
if(i == 3 || i == 5 || i == 6 || i == 9 || i == 10){
print ("Programming is Awesome!");
}
else {
print (i);
}
Better way By Using the modulo operator
if( i % 3 == 0 || i % 5 == 0){
print ("Programming is Awesome!");
}
else {
print (i);
}
Use can also try
print((i % 3 == 0 || i % 5 == 0)? "Programming is Awesome!" : i));

Undesired result with C# modulus operator

I was trying a simple exercise that shows on the screen all of the numbers that are multiples of 3 or 5 between 1-1000. As everyone knows the way to find this is using the modulus operator(%) and, if the modulus division returns 0 the number is multiple of 3 or 5, whatever you're comparing, very simple.
The point is that for some reason when I compare the expression if (i % 3 == 0 || i % 5 == 0) the first number that matches is 363.
When I compare only with 3 if (i % 3 == 0) the first number that matches is 105, and finally when I compare with only 5 if (i % 5 == 0) the result is as expected, starting from 5.
I would like to know what's going on here, or is just something so simple that I can't see at this time of the night due to I'm falling asleep.
static void Main(string[] args)
{
long total = 0;
for (int i = 3; i <= 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
total += i;
Console.WriteLine(i.ToString());
}
}
Console.Read();
}
Actually, it always displaying the correct result but you can't see them because of your Console size.
Try:
for (int i = 3; i <= 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
Console.WriteLine(i);
}
if (i % 100 == 0) Console.Read();
}
Press enter to see next 100 numbers.
Try redirecting your output to a file and looking at it. Use Program.exe > Output.txt to redirect and then open it in Notepad.

Determine if number is in the binary sequence 1 2 4 8 16 32 64 etc [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to check if a number is a power of 2
I want to determine if a number is in
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
...
I tried this:
public static void Main(string[] args)
{
int result = 1;
for (int i = 0; i < 15; i++)
{
//Console.WriteLine(result);
Console.WriteLine(result % 2);
result *= 2;
}
}
As you can see it returns
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...
How should I efficiently make the above print to be 0 for all of them including 1?
The following expression should be true if i is in your sequence.
(i & (i-1)) == 0)
http://rextester.com/JRH41036
How about something like this?
bool IsInBinarySequence( int number ){
var numbertocheck = 1;
do{
if( number == numbertocheck ) return true;
numbertocheck *= 2;
}while( numbertocheck <= number );
return false;
}
This has no specific limit on the number to check, but makes sure it stops checking if the number to check grows larger than the actual number we're trying to decide if is in the binary sequence.
Since the first time result is odd, you will get 1, since right after that you multiply it by 2, you will always get 0.
You need to print result if you want to get the list of powers of 2.
Console.WriteLine(result);
A primitive way to do that will be:
public static void Main(string[] args)
{
int result = 1;
int numToCheck = 141234;
boolean found = false;
for (int i = 0; i < 15; i++)
{
if (numToCheck == result) {
found = true;
break;
}
result *= 2;
}
if(found) Console.WriteLine("Awesome");
}
You can determine if a number is a power of 2 (including 2^0) by using the following method:
public bool IsPowerOfTwo(int x) {
return (x > 0) && ((x & (x - 1)) == 0)
}
Over here you can read why and how this works.
It's a bit of a hack, but this works ...
static void Main()
{
for (int i = 0; i < 40; i++)
{
var str = Convert.ToString(i, 2);
var bitCount = str.Count(c => c == '1');
Console.ForegroundColor = bitCount == 1 ? ConsoleColor.White : ConsoleColor.DarkGray;
Console.WriteLine(i + ": " + (bitCount == 1));
}
}
it seems you're actually asking if only one bit in the binary representation of the number is a 1
What you is not a test whether the number is in the sequence BUT it is a generator for such numbers... only the print part is containing some sort of a test...
Try this code for a test:
public static void Main(string[] args)
{
int result = 0;
int numToTest = 0;
if ( int.TryParse (args[0], out numToTest) )
{
result = ((from c in Convert.ToString (numToTest, 2) where c == '1' select c).Count() == 1 ) ? 1 : 0;
}
Console.WriteLine(result);
}
The above code takes a commandline argument and tests it for being in the binary sequence according to the criterion you posted... if so it prints 1, otherwise it prints 0.
Thats correct. 1 0 0 0 0 0 is the correct sequence.
Result is 1 in the first loop. 1 % 2 is 1.
Then result *= 2 gives result the value 2. In the next loop run 2 % 2 = 0. Then result *= 2 is 4. 4%2 is 0. 4 *= 2 is 8. 8 %2 is 0. Since result is always multiplied with 2 it keeps to be in the powers of 2 row and thus als MOD operations with 2 result to 0. So all is fine with that code.
your code will print only Binary sequences. as you are applying MOD 2 . so either you will get 0 or 1 . so it will be print in Binary Sequence.
Boolean result = false;
Int32 numberToTest = 64;
Int32 limit = 15;
for (int i = 0; i < limit && !result; i++)
{
if (Math.Pow(2, i).Equals(numberToTest))
{
result = true;
}
}
Console.WriteLine(String.Format("Number {0} {1} a power of 2.", numberToTest, result ? "is" : "is not"));

Categories

Resources