What's the matter? Afraid I might roll into your interview and ask you to sum all primes under 2 million?
*fizzbuzzes*
>>59740723
#include <stdio.h>
#include <math.h>
#define BELOW 2000000
int isaprime (int num);
int main (void) {
int i;
float sum = 0;
for (i = 2; i < BELOW; i++) {
if (isaprime(i) == 1) {
sum = sum + i;
printf ("\n%d\t%.1f", i, sum);
}
}
getch();
return 0;
}
int isaprime (int num) {
int i;
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0;
}
else {
;
}
}
return 1;
}
>>59741064
how do you explain the sqrt(num)
>>59741107
if the root is smaller than i it isn't a prime. this is due to the definition of primes.
>>59741064
>for (i = 2; i < BELOW; i++) {
Wrong. Start from 3, increment in 2. Start sum from 2. Which will also speedup(i = 2; i <= sqrt(num); i++) {, as you can also start from 3, and increment in 2 to sqrt(n) because you're only testing odds and even numbers won't divide odd.
>>59741126
>if the root is smaller than i it isn't a prime. this is due to the definition of primes.
No, it's because you'd be repeating already found pair factors, e.g. 2*4 = 8, 4*2 = 8, so you should have limited divisors to sqrt(8), as 2, 4 has already been found.
#include <iostream>
using namespace std;
int main()
{
int j , i;
int flag = 0;
int sum = 3;
for(i = 2; i <= 2000000;i++)
{
cout << i << endl;
for(j = 2; j < i; j++)
{
cout << i <<" % " << j << " = " << i % j << endl;
if((i % j) == 0)
{
flag = 0;
break;
}else
{
flag = 1;
continue;
}
}
cout << flag << endl;
if(flag == 1)
{
cout << i << " Is prime\n";
sum = sum + i;
}else if(flag == 0)
{
cout << i << " Is not prime\n";
}else
{
cout << "IDK...\n";
}
}
cout << sum << endl;
}