Exercise 2
Added Exercise 2 to repository
This commit is contained in:
21
Informatik_I/Exercise_2/task_3a/README.md
Normal file
21
Informatik_I/Exercise_2/task_3a/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Task
|
||||
|
||||
_Fibonacci numbers_ are the integers in the following sequence: $0, 1, 1, 2, 3, 5, 8, 13, 21, ...$. Each number is the sum of the two previous numbers.
|
||||
|
||||
_Fibonacci primes_ are Fibonacci numbers that are also prime numbers. Write a program that asks the user for an integer $m$ and then computes and prints all Fibonacci primes between $0$ and $m$ (including). Print each number on a new line.
|
||||
|
||||
Finally, on a new line print the total number of Fibonacci primes found.
|
||||
|
||||
## Example
|
||||
|
||||
If your program is asked to print the Fibonacci primes between $0$ and $14$ the output should look something like this:
|
||||
|
||||
```
|
||||
2
|
||||
3
|
||||
5
|
||||
13
|
||||
Found 4 Fibonacci primes
|
||||
```
|
||||
|
||||
**Important:** using anything other than `int` (e.g., `unsigned int`, floating point numbers, `long`, or double `long`) is forbidden.
|
47
Informatik_I/Exercise_2/task_3a/main.cpp
Normal file
47
Informatik_I/Exercise_2/task_3a/main.cpp
Normal file
@@ -0,0 +1,47 @@
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
int a = 1;
|
||||
int b = 1;
|
||||
int cnt = 0; // Initialization of number of deviders
|
||||
int count = 0; // Initialization of number of Fibonacci primes
|
||||
int n = 2; // Fibonacci number
|
||||
int i = 0; // Input variable
|
||||
|
||||
std::cin >> i;
|
||||
|
||||
for (; n <= i;) {
|
||||
// Reset counters
|
||||
cnt = 0;
|
||||
|
||||
// Check for deviders of Fibonacci number
|
||||
if (n <= 22360) {
|
||||
for (int j = 1; j <= 22360; ++j) { // 22360 = sqrt(500000000)
|
||||
if (n % j == 0) {
|
||||
++cnt;
|
||||
}
|
||||
}
|
||||
// Increase count if Fibonacci number is a prime number
|
||||
if (cnt == 2) {
|
||||
std::cout << n << "\n";
|
||||
++count;
|
||||
}
|
||||
} else if (n > 22360) {
|
||||
for (int j = 1; j <= 22360; ++j) { // 22360 = sqrt(500000000)
|
||||
if (n % j == 0) {
|
||||
++cnt;
|
||||
}
|
||||
}
|
||||
if (cnt == 1) {
|
||||
std::cout << n << "\n";
|
||||
++count;
|
||||
}
|
||||
}
|
||||
// Initialize next Fibonacci number
|
||||
a = b;
|
||||
b = n;
|
||||
n = a + b;
|
||||
}
|
||||
// End message
|
||||
std::cout << count << "\n";
|
||||
}
|
Reference in New Issue
Block a user