Prime numbers up to N
Write a function bool isPrime(int n) that checks whether a number is prime, and use it to print all prime numbers from 2 to N.
Example
Input
20Output
2 3 5 7 11 13 17 19A test on functions: writing a function with parameters and a return value, logical functions (bool), functions that work with the digits of a number, and passing parameters by reference. This page is new – the tasks are in two groups, with solutions.
return – returns a value and ends the function immediatelybool isPrime(int n)) and using them in if% 10 and / 10) inside a functionint &x)| Points | 0–11 | 12–16 | 17–21 | 22–26 | 27–30 |
|---|---|---|---|---|---|
| Grade | 1 | 2 | 3 | 4 | 5 |
The scale is a suggestion for self-assessment; the teacher can adapt it. (In Serbian schools grades go from 1 to 5, where 5 is the best.)
Write a function bool isPrime(int n) that checks whether a number is prime, and use it to print all prime numbers from 2 to N.
202 3 5 7 11 13 17 19Write a function int digitSum(int x). Read n natural numbers and print the one with the largest digit sum (if there are several – the first one).
4
123 99 405 1899Write a function int gcd(int a, int b) (Euclid's algorithm). Read the numerator and the denominator and print the simplified fraction in the form a/b.
12 182/37 57/5Write a function long long factorial(int n) and use it to compute the number of ways to choose a team of k from n students: C(n, k) = n! / (k! · (n − k)!). It holds that 0 ≤ k ≤ n ≤ 20.
5 21020 10184756Write a function bool isPalindrome(int x) that checks whether a number reads the same from left to right and from right to left. For a given interval [a, b] print all such numbers and how many there are.
10 5011 22 33 44
Total: 4Write a function void swapValues(int &x, int &y) and a function void sort3(int &a, int &b, int &c) that arranges three numbers from the smallest to the largest. Read three numbers, sort them by calling the function and print them.
7 2 52 5 7& are copies: a change inside the function does not change the variable in main.return.1. What does a function of type void return?
2. After the call f(x), where void f(int a) { a = 5; }, what is x if it was 2 before?
3. How do you write a parameter that the function can change in the caller?