Originally Posted by
jewleeuhn
Hello fellow programmers,
I'm a bit new to programming, and I am trying to create a function that reports prime numbers between a number k and a number secondnum. Here's where I am so far:
Code:
void prime_number(int k, int secondnum)
{
int i;
int m;
int j = secondnum;
for (i = k; i<=j; i++)
{
m = i;
m = m%2;
if(m!=0)
{
printf("%d is a prime number.\n", i);
continue;
}
}
}
When I call the function, when k = 1 and secondnum = 5, it prints out:
1 is a prime number.
3 is a prime number.
5 is a prime number.
3 is a prime number.
....
I'm not sure why it prints out the same number multiple times. Any help is appreciated!
Hi. A couple of things..
I rewrote the program so that it would function as you were expecting it to work. Here's what I ended up with:
Code:
#include <stdio.h>
void prime_number(int k, int secondnum);
int main(void) {
prime_number(1,11);
}
void prime_number(int k, int secondnum) {
int m;
while( k <= secondnum) {
m = k;
m %=2;
if(m != 0) {
printf("%d is a prime number.\n", k);
}
k++;
}
}
I'm sure it's not the cleanest code. But, it'll do.
So, a few things. I think a "while" statement here will suit you better. It'll help you reduce unnecessary variables.
Another thing, I removed the "continue" from the if statement.
And finally, this isn't testing if a number is prime, it's testing if it's odd.
Prime numbers are only divisible by 1 and themselves. So, when you hit numbers like 9, 15, 21, etc., you'll start getting "false positives".
Although I do like the "first number, second number" bit. Once you get your formula worked out, you can find all of the prime numbers within a range of two different ones. Never though about doing it that way.
Also, if you're working with Primes, you may want to look into Goldbach's Conjecture.