Im trying to write a program to print all the primes from 1 to 100. I am however required to use a boolean function. My problem is that all the odd #s except 1 also appear in the output.

#include "stdafx.h"
#include <stdio.h>
#include "strlib.h"
#include "genlib.h"
#include "random.h"
#include <math.h>

bool IsPrime(int num);

int main()
{
	int num;

	num=2;
	printf("The prime numbers in the range of 1-100 are:\n");
	printf("%d\n", num);
	for (num=3;num<=100;num+=2)
	{
		if (IsPrime(num)==(true));
		{
			printf("%d\n", num);
		}
	}
}
	
bool IsPrime(int num)
{
	int i; 
	double limit;

	if (num<=1) return (false);
	if (num==2) return (true);
	if (num%2==0) return (false);
	limit=sqrt(double(num))+1;
	for (i=3;i<=limit;i+=2)
	{
		if (num%i==0) return (false);
	}
	return (true);
}

Recommended Answers

All 3 Replies

Use code tags and format you code please, it's hard to read. :)
You can't make a boolean function in C. Use int instead (zero and nonzero).
Why do you have so meany headers? All you need is stdio.h and math.h

Also, I think the line:

limit=sqrt(double(num))+1;

Was ment to be:

limit=sqrt((double)num)+1;

Apart from what Hiroshe has rightly stated,I would like to add these (after all corrections stated by Hiroshe):

1>

if (IsPrime(num)==(true));
{
printf("%d\n", num);
}

No semicolon at the end of if and don't do redundant work as in IsPrime(num)==(true) the following is enough:

if (IsPrime(num)) //No semicolon and a return of 1 is enough no need to recheck with "==" op.
{
printf("%d\n", num);
}

2>
And in your IsPrime function with this line :

for (i=3;i<=limit;i+=2)

You can still cut down the number of checks by checking only with the prime numbers <=limit as the rule says "If a number cannot be completely divided by any prime number <= its square root then that number is a prime".
Of course this doesn't matter much when the limit is 100 but for higher limits it counts a lot.

Thanks for the help. It seems the semi-colon was the only problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.