kid a function can return only one value hence when it is called from main it will show only the final value r takes in the function .But then your question would be that we should have got 7. The answer is :
1/ do not start 'a' with value 1, initialize with 2.I mean 1 divides everything.
2/Do not use a return type function in this case.
3/ try this code it will work:
It gave 1 as a prime because int m arrived in the function as '0' and was incremented on the fifth line of the function there z = (m+1). You could fix this by only allowing positive non-zero integers to be passed to the function. Another way of fixing this would be to trial division by all integers, including 1, and if it has exactly two divisors, then returning it as a prime.
Once you have this working, then you can work on speeding up your method. You need only check up to the square root of a number to see if it is prime and other than 2, you only need to divide by odd numbers*.
To check if somthing is prime, start with 2. If the number can be devided in 2 (even once) it is not prime. Next, divide by every sequential odd number:
//prototype
bool isprime(/* args */)
//assume 'x' = int that we want to tell is prime or not
switch((x % 2) == 0)
{
casetrue:
{
//true, we can devide by two, so it can't be prime!
}
break;
casefalse:
{
//false, try every other odd number
for(unsignedlongint y = 3; y < A_LIMIT; y += 2)
{
//I'll leave the logic to you
}
}
break;
default:
break;
}
That's just pseudo code to get you thinking. Hope this helps.
----------------------------------------------------------------------------------
Also, mats, you absolutely do not want to include 1!!! You should not check every integer, and just because it has two devisors does not make it prime. Every number has 2 devisors (1 and itself), so by your definition every number is prime, which is not true.
A prime number is a number that has only two devisors (1 and itself). That is why you should not test 1, because you will always get a valid result from that operation.
Half of all numbers are even. Since all even numbers can be devided by 2, you can use modulo to narrow your results significantly. Aftwerwards, if it is still "prime", you just check every odd number after 2.