C program to print all the prime numbers from 1-300 - c

I have written this code for C to print prime numbers from 1-300
GNU GCC Compiler shows the following error:
error: invalid operands to binary % (have ‘double’ and ‘int’)
if (sqrt(num) == 0 || sqrt(num) % 2 != 0)
My code is this:
#include <stdio.h>
#include <math.h>
int main() {
/*Created by Suvid Singhal Date:- January 2, 2017*/
int num;
printf("Welcome to 1-300 prime numbers C Program!!!");
for (num = 0; num <= 300; num++) {
if (sqrt(num) == 0 || sqrt(num) % 2 != 0) {
printf("%d\n", num);
} else {
continue;
}
}
return 0;
}

You have lots of thing going wrong in your answer.
Let's check them one by one.
Your idea about prime number is not clear. A prime number has no divisior except the number and 1. (1 is not a prime number).
How to check if a number is prime or not?
You can check all the `numbers <=square root of (x). So you need to check if someone (except 1 ) divides the number. If yes then it is not prime else it is.
Implementation Details
int check= 0;
for(int i=2;i<=(int) sqrt(x);i+=1)
if(n%i == 0)
{
check = 1;
n is non-prime;
break; // no need to check
}
if(check == 0)
n is prime
sqrt() return double and ...
Modulous can be applied over an int so you have to cast it to that.
If you want to avoid it all
for(int i=2;i*i<=x;i++)
...
For you to study
Learn about sieve method to get the primes. For 300 numbers probably it doesn't matter what you use but in case it is 10000000 then you will definitely want to give it a read.

% operator is for integers. You may want to use fmod() or an integer cast.
if ( sqrt( num ) == 0 || fmod( sqrt( num ), 2 ) != 0 )
or
if ( sqrt( num ) == 0 || (int) sqrt( num ) % 2 != 0 )
This should fix your compilation errors.
ps: If you are looking for an awesome way to generate prime numbers, see Sieve of Erastosthenes

In the code sample you have given, it is not quite clear how you intend to determine whether a number is prime or not. You have the following condition if (sqrt(num) == 0 || sqrt(num) % 2 != 0) to apparently determine a number as prime. But this condition is syntactically invalid. As others have pointed out, you can't do modulo operation on a non-int number as returned by the sqrt function. What value, do you think, is returned by the operation sqrt(num) % 2 and what has it do with a number being prime? Your usage of continue has also no importance. Maybe you are a little confused between break and continue. I am giving you a sample program. Try to learn what your mistakes are from this:
int isPrime = 1;
for(int i=2;i<=300;i++) {
isPrime = 1;
for(int j=2; j!=i && j <= ceil(sqrt(i));j++) {
if(i%j == 0) {
//Not a prime number
isPrime = 0;
break;
}
}
if(isPrime) {
printf("%d\n", i);
}
}

Changing
if( sqrt(num) == 0 || sqrt(num) % 2!=0 )
to
if( sqrt(num) == 0 || (int)sqrt(num) % 2!=0 )
Should fix compilation errors. See error: invalid operands to binary % when taking modulus of float for more info.

Related

Trying to find prime numbers

I'm a first year student in a programming university and my first assignment is to find the sum of prime numbers between 3990000000 and 4010000000. The problem is everything I do, when I run the program it says the sum is 0 with a return value of 25. I've been trying to debug this code but with no luck, could someone help me?
My code is:
#include <stdio.h>
#define STARTNUMBER 3990000000
#define ENDNUMBER 4010000000
int main() {
unsigned int num;
int j, c, flag, sum = 0;
flag = 1;
c = 5;
j = 7;
for (num = STARTNUMBER; num <= ENDNUMBER; num++) {
if (num % 2 == 0) { /*if number mod 2 equals zero go to next number*/
flag = 0;
break;
}
if (num % 3 == 0) { /*if number mod 3 equals zero go to next number*/
flag = 0;
break;
} else
/*check if number is prime with the sequences 5+6+6...<=sqrt(number) and 7+6+6..<=sqrt(number)*/
while (c * c <= num && j * j <= num && flag == 1) {
if (num % c == 0 || num % j == 0) {
flag = 0;
break;
}
c += 6;
j += 6;
}
if (flag == 1)
sum++;
}
printf("There are %d prime numbers", sum);
}
You are asking for the sum of the prime number, even if your code is just printing how many they are. Assuming you've misunderstood the exercise, I try to show a possible problem of your original question, glimpsing a possible trick in your exercise since the interval is very close to 232.
Assuming also you are on a 64-bit environment, if there are at least two prime numbers in that inteval, the sum is going to be greater than INT_MAX (231 - 1). An int is not sufficient to store a value, and also unsigned int is not sufficient since UINT_MAX is 232 - 1.
Finally, assuming you've solved your problems with the break statements already described in the comments, try to store your sum variable into a unsigned long int, and replace the last part of the loop with
if (flag==1)
sum += num;

Sphere Online Judge Issues (Prime Number Generator)

Ok, so I enjoy using SPOJ to practice programming and developing algorithms. I always have issues with the questions though. A lot of times, I will get a "wrong answer" message when clearly my code answers the questions properly. If someone could tell me if there is anything wrong or why SPOJ would be telling me my answer was wrong that would be awesome! Here is the problem word-for-word:
Prime Number Generator
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
My code:
int n;
scanf("%d", &n);
if(n > 10){ return 0; }
n = n*2;
int arr[n];
for(int i = 0; i < n; i++){ scanf("%d", &arr[i]); }
for(int i = 0; i < n; i += 2){
if(arr[i] >= 1 && arr[i] <= arr[i+1] && arr[i+1] <= 1000000000 && arr[i+1]-arr[i] <= 100000){
for(int j = arr[i]; j <= arr[i+1]; j++){
if(j % 2 == 1 || j == 2){
printf("%d\n", j);
}
}
printf("\n");
}
}
return 0;
INPUT:
2
7 11
2 9
OUTPUT:
7
9
11
2
3
5
7
9
A lot of times, I will get a "wrong answer" message when clearly my code answers the questions properly.
This is not one of those cases as evidenced by the fact that, despite the contrary, your code seems to think that 9 is a prime. The line:
if(j % 2 == 1 || j == 2)
combined with the fact that you appear to be printing all odd numbers (and two), is an indication that your prime check is incorrect.
Where you should probably start is with a simple prime check function such as:
int isPrime(int num) {
int chk = 2;
while (chk * chk <= num)
if ((num % chk) == 0)
return 0;
++chk;
}
return 1;
}
Once you have it working, then worry about performance (two of my favourite mantras are "Wrong is the least optimised state" and "Get it working first, then get it working fast").
The things you can look into for optimisations include, but are not limited to:
Eratosthenes sieve where, provided the range of primes isn't too large, it can greatly improve speed by not having to do a lot of calculations for each prime test; and
Using the fact that all primes other than two and three are of the form 6n±1, effectively tripling the speed of the isPrime function (see here for an explanation).
For that second bullet point, you can use:
int isPrime(unsigned int num) {
// Special cases for 0-3.
if (num < 2) return 0;
if (num < 4) return 1;
int chk = 5, add = 2; // prime generator, 6n +/- 1.
while (chk * chk <= num) // check every candidate.
if ((num % chk) == 0) // check if composite.
return 0;
chk += add; // next candidate.
add = 6 - add; // alternate +2, +4.
}
return 1; // no factors, must be prime.
}

Find out max divisor of a positive integer

I need to find the biggest divisor of a positive integer and output it. Divisor should not be 1 or be equal to the integer itself. If it's a prime number the output should be "0". I have this code so far. However it doesn't work. It only works when I use "break" instead of "return 0" statement, but according to the task I should not use break :( How can I fix it? Thnx
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
scanf("%d", &input);
for ( ; div <= input/2; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
return 0;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
You can rewrite it this way
int main(){
int input, maxDiv = 0;
int div = 2;
scanf("%d", &input);
for(; !maxDiv; div++)
if(!(input%div))
maxDiv = input/div;
printf("%d\n", ( maxDiv == 1 || input < 0 ? 0 : maxDiv ) );
return 0;
}
It is an infinite loop that will exit as soon as maxDiv != 0. The complexity is O(sqrt (n)) as there is always a divisor of n less than or equal to sqrt(n), so the code is bound to exit (even if input is negative).
I forgot, you have to handle the case where input is zero.
Maybe you can declare a flag?
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
char found = 0;
scanf("%d", &input);
for ( ; div <= input/2 && !found ; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
found = 1;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
You can stop the loop when you reach sqrt(input)... it's not that difficult to find a perfectly good integer sqrt function.
There's not a lot of point dividing by all the even numbers after 2. In fact there's not a lot of point dividing by anything except the primes. It's not hard to find the primes up to sqrt(INT_MAX) (46340, for 32-bit integer)... there are tables of primes freely available if you don't want to run a quick sieve to generate same.
And the loop...
maxdiv = 0 ;
i = 0 ;
sq = isqrt(input) ;
while ((maxdiv == 0) && (prime[i] < sq))
{
if ((input % prime[i]) == 0)
maxdiv = input / prime[i] ;
i += 1 ;
} ;
assuming a suitable integer sqrt function and a table of primes... as discussed.
Since you are looking for the largest divisor, is there a reason you're not looping backward to 2? If there isn't, then there should be no need for a break statement or any special logic to exit the loop as you should keep looping until div is greater than input / 2, testing every value until you find the largest divisor.
maxDiv = -1;
for (div = input / 2;
div >= 2 && maxDiv == -1;
--div)
{
if (input % div == 0)
maxDiv = div;
}
maxDiv += (maxDiv == -1);
printf ("%d\n", maxDiv);
I added the extra condition of maxDiv being -1, which is like adding a conditional break statement. If it is still -1 by the end of the loop, then it becomes 0 because maxDiv += 1 is like writing maxDiv = -1 + 1, which is 0.
Without any jump statement such as break, this sort of test is what you must do.
Also, regarding your code, if I input 40, the if statement will be triggered when div is 2, and the program will end. If the return 0 is changed to a break, maxDiv will be 2, not 20. Looping backward will find 20 since 40/2=20, and 40%20==0.
Let us denote D to the max divisor of a given composite number N > 1.
Then, obviously, the number d = N / D is the min non-trivial divisor of N.
If d would not a primer number, then d would have a non-trivial divisor p < d.
By transitivity, this implies that p is a divisor of N, but this fact would contradict the fact that d is the min divisor of N, since p < d.
So, d must be a prime number.
In particular, it is enouth to search over those numbers which are less than sqrt(N), since, if p is a prime number greater than sqrt(N) which divies N, then N / p <= sqrt(N) (if not, *p * (N / p) > sqrt(N)sqrt(N) == N, wich is absurd).
This shows that it's enough to do the search the least divisor d of N just within the range of primer numbers from 2 to sqrt(N).
For efficiency, the value sqrt(N) must be computed just once before the loop.
Moreover, it is enough a rough approximation of sqrt(N), so we can write:
#include <math.h>
#include <stdio.h>
int main(void)
{
int N;
scanf("%d",&N);
// First, we discard the case in that N is trivial
// 1 is not prime, but indivisible.
// Change this return if your want.
if (N == 1)
return 0;
// Secondly, we discard the case in that N is even.
if (N % 2 == 0)
return N / 2;
// Now, the least prime divisor of N is odd.
// So, we increment the counter by 2 in the loop, by starting in 3.
float sqrtN = fsqrt(N); // square root of N in float precision.
for(d = 3; d <= sqrtN; d += 2)
if (N % d == 0)
return N/d;
// If the loop has reached its end normally,
// it means that N is prime.
return 0;
}
I think that the problem is not well stated, since I consider that a better flag to signalize that N is prime would be a returned value of 1.
There are more efficient algorithms to determine primality, but they are beyond the scope of the present question.

Check to see if integer is one in which each digit is either a zero or a one

What is the efficient way in C program to check if integer is one in which each digit is either a zero or a one ?
example 100 // is correct as it contains only 0 or 1
701 // is wrong
I tried for
int containsZero(int num) {
if(num == 0)
return 0;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 0)
return 0;
num /= 10;
}
return -1;
}
int containsOne(int num) {
if(num == 0)
return 0;
if(num < 0)
num = -num;
while(num > 0) {
if(num % 10 == 1)
return 0;
num /= 10;
}
return -1;
}
You can peel of every digit and check it. This takes O(n) operations.
int input;
while (input != 0)
{
int digit = input %10; //get last digit using modulo
input = input / 10; //removes last digit using div
if (digit != 0 && digit != 1)
{
return FALSE;
}
}
return TRUE;
Well, in the worst case you have to check every digit, so you cannot have an algorithm better than O(d), where d is the number of digits.
The straight-forward approach satisfies this:
int n = 701;
while ( n != 0 && (n % 10) <= 1 )
{
n /= 10;
}
if ( (n % 10) > 1 )
{
printf("Bad number\n");
}
else
{
printf("Good number\n");
}
This assumes positive numbers though. To put it into a general function:
int tester(int n)
{
if ( n < 0 )
{
n = -n;
}
while ( n != 0 && (n % 10) <= 1 )
{
n /= 10;
}
return ( (n % 10) <= 1 );
}
Demo: http://ideone.com/jWyLdl
What are we doing here? We check if the last decimal digit (n % 10) is either 0 or 1, then cut of the last digit by dividing by ten until the number is 0.
Now of course there is also another approach.
If you are guaranteed to have e.g. always 32bit integers, a look-up table isn't that large. I think it may be around 2048 entries, so really not that big.
You basically list all valid numbers:
0
1
10
11
100
101
110
111
...
Now you simply search through the list (a binary search is possible, if the list is sorted!). The complexity with linear search would be, of course, worse than the approach above. I suspect binary search beeing still worse in actual performance, as you need to jump a lot in memory rather than just operating on one number.
Anything fancy for such a small problem is most probably overkill.
The best solution I can think of, without using strings:
while(n)
{
x = n%10;
if(x>1)
return -1;
n /= 10;
}
return 0;
Preamble
Good straightforward algorithms shown in other answer are O(n), being n the number for the digits. Since n is small (even using 64bit integer we won't have more than 20 digits), implementing a "better" algorithm should be pondered, and meaning of "efficient" argued; given O(n) algorithms can be considered efficient.
"Solution"
We can think about sparse array since among 4 billions of numbers, only 2^9 (two symbols, 9 "positions") have the wanted property. I felt that some kind of pattern should emerge from bits, and so there could be a solution exploiting this. So, I've dumped all decimal numbers containing only 0 and 1 in hex, noticed a pattern and implemented the simplest code exploiting it — further improvements are surely possible, e.g. the "table" can be halved considering that if x is even and has the property, then x+1 has the property too.
The check is only
bool only01(uint32_t n)
{
uint32_t i = n & 0xff;
uint32_t r = n >> 8;
return map01[i][0] == r || map01[i][1] == r;
}
The full table (map01) and the test code are available at this gist.
Timing
A run of the test ("search" for numbers having the property between 0 and 2 billions — no reason to go beyond) with my solution, using time and redirecting output to /dev/null:
real 0m4.031s
user 0m3.948s
A run of the same test with another solution, picked from another answer:
real 0m15.530s
user 0m15.221s
You work with base 10, so, each time check the % 10:
int justOnesAndZeros(int num) {
while ( num )
{
if ( ( num % 10 != 1 ) && ( num % 10 != 0 ) )
{
return FALSE;
}
num /= 10;
}
return TRUE;
}

Prime number in C

int prime(unsigned long long n){
unsigned val=1, divisor=7;
if(n==2 || n==3) return 1; //n=2, n=3 (special cases).
if(n<2 || !(n%2 && n%3)) return 0; //if(n<2 || n%2==0 || n%3==0) return 0;
for(; divisor<=n/divisor; val++, divisor=6*val+1) //all primes take the form 6*k(+ or -)1, k[1, n).
if(!(n%divisor && n%(divisor-2))) return 0; //if(n%divisor==0 || n%(divisor-2)==0) return 0;
return 1;
}
The code above is something a friend wrote up for getting a prime number. It seems to be using some sort of sieving, but I'm not sure how it exactly works. The code below is my less awesome version. I would use sqrt for my loop, but I saw him doing something else (probably sieving related) and so I didn't bother.
int prime( unsigned long long n ){
unsigned i=5;
if(n < 4 && n > 0)
return 1;
if(n<=0 || !(n%2 || n%3))
return 0;
for(;i<n; i+=2)
if(!(n%i)) return 0;
return 1;
}
My question is: what exactly is he doing?
Your friend's code is making use of the fact that for N > 3, all prime numbers take the form (6×M±1) for M = 1, 2, ... (so for M = 1, the prime candidates are N = 5 and N = 7, and both those are primes). Also, all prime pairs are like 5 and 7. This only checks 2 out of every 3 odd numbers, whereas your solution checks 3 out of 3 odd numbers.
Your friend's code is using division to achieve something akin to the square root. That is, the condition divisor <= n / divisor is more or less equivalent to, but slower and safer from overflow than, divisor * divisor <= n. It might be better to use unsigned long long max = sqrt(n); outside the loop. This reduces the amount of checking considerably compared with your proposed solution which searches through many more possible values. The square root check relies on the fact that if N is composite, then for a given pair of factors F and G (such that F×G = N), one of them will be less than or equal to the square root of N and the other will be greater than or equal to the square root of N.
As Michael Burr points out, the friend's prime function identifies 25 (5×5) and 35 (5×7) as prime, and generates 177 numbers under 1000 as prime whereas, I believe, there are just 168 primes in that range. Other misidentified composites are 121 (11×11), 143 (13×11), 289 (17×17), 323 (17×19), 841 (29×29), 899 (29×31).
Test code:
#include <stdio.h>
int main(void)
{
unsigned long long c;
if (prime(2ULL))
printf("2\n");
if (prime(3ULL))
printf("3\n");
for (c = 5; c < 1000; c += 2)
if (prime(c))
printf("%llu\n", c);
return 0;
}
Fixed code.
The trouble with the original code is that it stops checking too soon because divisor is set to the larger, rather than the smaller, of the two numbers to be checked.
static int prime(unsigned long long n)
{
unsigned long long val = 1;
unsigned long long divisor = 5;
if (n == 2 || n == 3)
return 1;
if (n < 2 || n%2 == 0 || n%3 == 0)
return 0;
for ( ; divisor<=n/divisor; val++, divisor=6*val-1)
{
if (n%divisor == 0 || n%(divisor+2) == 0)
return 0;
}
return 1;
}
Note that the revision is simpler to understand because it doesn't need to explain the shorthand negated conditions in tail comments. Note also the +2 instead of -2 in the body of the loop.
He's checking for the basis 6k+1/6k-1 as all primes can be expressed in that form (and all integers can be expressed in the form of 6k+n where -1 <= n <= 4). So yes it is a form of sieving.. but not in the strict sense.
For more:
http://en.wikipedia.org/wiki/Primality_test
In case the 6k+-1 portion is confusing, note that you can perform some factorization of most forms of 6k+n and some are obviously composite and some need to be tested.
Consider numbers:
6k + 0 -> composite
6k + 1 -> not obviously composite
6k + 2 -> 2(3k+1) --> composite
6k + 3 -> 3(2k+1) --> composite
6k + 4 -> 2(3k+2) --> composite
6k + 5 -> not obviously composite
I've not seen this little trick before, so it's neat, but of limited utility since a sieve of Eratosthenese is more efficient for finding many small prime numbers, and larger prime numbers benefit from faster, more intelligent, tests.
#include<stdio.h>
int main()
{
int i,j;
printf("enter the value :");
scanf("%d",&i);
for (j=2;j<i;j++)
{
if (i%2==0 || i%j==0)
{
printf("%d is not a prime number",i);
return 0;
}
else
{
if (j==i-1)
{
printf("%d is a prime number",i);
}
else
{
continue;
}
}
}
}
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}

Resources