# day09 - Exercise Write a program that reads a number from...

This preview shows pages 1–5. Sign up to view the full content.

1 Exercise Write a program that reads a number from the user and tells whether it is prime, and if not, gives the next prime after it. Sample runs : (run #1) Type a number: 29 29 is prime (run #2) Type a number: 14 14 is not prime; the next prime after 14 is 17 As part of your solution, you should write the following functions: is_prime : Returns true if the parameter passed is a prime number. next_prime : Returns the next prime number whose value is greater than or equal to the parameter passed.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Solution #include <stdio.h> #include <stdbool.h> void print_prime_status(int num); int next_prime(int num); bool is_prime(int num); int main() { printf("Type a number: "); int num; scanf("%d", &num); print_prime_status(num); } // prints that primality status of a number; if // it's not prime, it computes the next one and prints // that too void print_prime_status(int num) { if (is_prime(num)) { printf("%d is prime\n", num); } else { printf("%d is not prime; the next prime after %d is %d\n", num, num, next_prime(num)); } }
3 Solution // returns the next prime that is greater than // or equal to the number given int next_prime(int num) { while (!is_prime(num)) { num++; } return num; } // returns true if the number given is a prime number bool is_prime(int num) { if (num <= 1) { return false; } for (int i = 2; i < num; i++) { if (num % i == 0) { return false; } } return true; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 Exercise Modify your program from the previous slide so that it reads two numbers and tells whether each number is prime, and if not, gives the
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 04/29/2009 for the course EE 142 taught by Professor Bensollimketkai during the Spring '09 term at Washington State University .

### Page1 / 16

day09 - Exercise Write a program that reads a number from...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online