I'm writing a program to calculate the number of prime numbers in a sequence. There's a variable called num that is given and then the program must calculate how many prime numbers there are from 2 (the smallest prime number) to num.
It should be something like that:
_________________________________________________
Enter a number greater than 1: 7
There are 4 prime numbers between 2 and 7.
__________________________________________________ _______________
This is because 2,3,5 and 7 are prime numbers, a total of 4 numbers.
The code below shows the variable num which is equal to 7, the main function calls isPrime (which says if a number is prime or not), then the way I thought about was using a for loop from 2 to num and check if each i is prime or not.
I don't know how to proceed from that. Please, could someone help?
[COLOR=var(--highlight-keyword)][code]
#[COLOR=var(--highlight-keyword)]include[/COLOR] [COLOR=var(--highlight-variable)]<stdio.h>[/COLOR][/COLOR]
[COLOR=var(--highlight-keyword)]#[COLOR=var(--highlight-keyword)]include[/COLOR] [COLOR=var(--highlight-variable)]<math.h>[/COLOR][/COLOR]
[COLOR=var(--highlight-namespace)]int[/COLOR] [COLOR=var(--highlight-literal)]isPrime[/COLOR]([COLOR=var(--highlight-namespace)]int[/COLOR] num) {
[COLOR=var(--highlight-namespace)]int[/COLOR] i;
[COLOR=var(--highlight-keyword)]for[/COLOR] (i=[COLOR=var(--highlight-namespace)]2[/COLOR]; i<=[COLOR=var(--highlight-literal)]sqrt[/COLOR](num); i++) {
[COLOR=var(--highlight-keyword)]if[/COLOR] (num%i == [COLOR=var(--highlight-namespace)]0[/COLOR]) {
[COLOR=var(--highlight-keyword)]return[/COLOR] [COLOR=var(--highlight-namespace)]0[/COLOR];
}
}
[COLOR=var(--highlight-keyword)]return[/COLOR] [COLOR=var(--highlight-namespace)]1[/COLOR];
}
[COLOR=var(--highlight-namespace)]int[/COLOR] [COLOR=var(--highlight-literal)]main[/COLOR](){
[COLOR=var(--highlight-namespace)]int[/COLOR] i, num, numofprimes;
num=[COLOR=var(--highlight-namespace)]7[/COLOR];
[COLOR=var(--highlight-keyword)]for[/COLOR] (i=[COLOR=var(--highlight-namespace)]2[/COLOR];i<=num;i++){
[COLOR=var(--highlight-keyword)]if[/COLOR] (isPrime(i)){
}
[COLOR=var(--highlight-literal)]printf[/COLOR]([COLOR=var(--highlight-variable)]"%d"[/COLOR], numofprimes);
}
[COLOR=var(--highlight-keyword)]return[/COLOR] [COLOR=var(--highlight-namespace)]0[/COLOR];
}[code/]
If someone could help I would be glad.