Thursday, July 30, 2009

Figuring out if input is a Prime Number in C using loop?

I need to know if an integer the user inputs is a prime number. There is no limit to the value the user can input.


How do I do this?





Take note that this is just for C.

Figuring out if input is a Prime Number in C using loop?
i presume you are trying to get others to do your homework for you. anyways, let me start you off with the definition of a prime number. if a natural number is not a multiple of another natural number then its a prime. so a simple way is to in a loop divide it with each number less than it and see if there's a remainder.
Reply:I dont know the code for C but the argument should be whether it can be divided by itself or 1 only.


So having res values (5.12345)in the answer when dividing should be your key factor.





Alternatively you can hard code the prime factors and then cross check against them (not recommendable i suppose)
Reply:this is how I usually do it (may not be the best method)


If you are going to be calling this function a lot, it would be a good idea to store known primes in a vector or array and check the input against it before running this function.





code: http://rafb.net/p/obo7Zd18.html
Reply:If there is no limit to the input value, you will have to be able to store and test values greater than the maximum of the longest integer type available on your compiler, no matter what that is. As a first step, you can write your own functions to do arithmetic between numbers stored as sequences of decimal digits in character strings, then use those functions to divide the user's input by all possible divisors until the remainder is zero (input is not prime) or the quotient is less than the divisor (input is prime), whichever happens first.





As a first improvement, after testing for division by 2 and 3, start the divisor at 5 then increment it by 2 and 4 alternately. This will avoid trying divisors which are multiples of 2 or 3.





Even that method will run out of steam on input numbers of 18 or 20 digits. For larger numbers, check Chris Caldwell's prime pages at the link below. They are the best resource on the whole worldwide web for anything to do with prime numbers, but the methods which he refers to for proving the primeness of large numbers are using deep theoretical stuff that is understood by very few mathematics students even at university.


No comments:

Post a Comment