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

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

View Full Document Right Arrow Icon
    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.
Background image of page 1

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

View Full DocumentRight Arrow Icon
    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)); } }
Background image of page 2
    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; }
Background image of page 3

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

View Full DocumentRight Arrow Icon
    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
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

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 Right Arrow Icon
Ask a homework question - tutors are online