Skip to content

Instantly share code, notes, and snippets.

@ervinod
Last active August 9, 2023 04:24
Show Gist options
  • Select an option

  • Save ervinod/4efad03b669f6991804b690b255fd2a9 to your computer and use it in GitHub Desktop.

Select an option

Save ervinod/4efad03b669f6991804b690b255fd2a9 to your computer and use it in GitHub Desktop.
problem-5
void main() {
//write a program to print prime nos from 1 to n
//Note: prime number is only divisible by 1 and itself.
int no = 50;
// check for the every number from 1 to no
for (int i = 1; i <= no; i++) {
if (isPrime(i)) {
print("$i");
}
}
//output 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47
}
bool isPrime(int no) {
// since 0 and 1 is not prime number return false.
if (no == 0 || no == 1) return false;
// Run a loop from 2 to n/2
for (int i = 2; i <= no / 2; i++) {
// if the number is divisible by i, then n is not a
// prime number, otherwise n is prime number.
if (no % i == 0) return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment