Skip to content

Commit

Permalink
moved some snippets from C++ to C
Browse files Browse the repository at this point in the history
  • Loading branch information
ashukr07 committed Jan 10, 2025
1 parent f95b751 commit 5a6d50b
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,24 @@ tags: math, perfect-number
author: ashukr07
---

```cpp
```c
#include <stdbool.h>

// Function to check if a number is a perfect number
bool is_perfect(int n) {
if (n <= 1) return false;

int sum = 1; // 1 is a divisor for all n > 1
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
sum += i;
if (i != n / i) sum += n / i;
}
}
return sum == n && n != 1;
return sum == n;
}

// Usage:
// Usage
is_perfect(28); // Returns: true
is_perfect(12); // Returns: false
```
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@ tags: math, finance
author: ashukr07
---

```cpp
#include <cmath>
```c
#include <math.h>

// Function to calculate compound interest
double compound_interest(double principal, double rate, double time, int n) {
return principal * std::pow(1 + rate / n, n * time);
return principal * pow(1 + rate / n, n * time);
}

// Usage:
double principal = 1000.0; // Initial amount
double rate = 0.05; // Annual interest rate (5%)
double time = 2; // Time in years
int n = 4; // Compounded quarterly

compound_interest(principal, rate, time, n); // Returns: 1104.081632653061
```
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ tags: math, fibonacci, recursion
author: ashukr07
---

```cpp
```c
// Function to calculate the nth Fibonacci number
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ tags: math, digits
author: ashukr07
---

```cpp
```c
// Function to calculate the sum of the digits of an integer
int sum_of_digits(int n) {
int sum = 0;
while (n != 0) {
Expand Down
16 changes: 0 additions & 16 deletions snippets/cpp/math-and-numbers/factorial.md

This file was deleted.

0 comments on commit 5a6d50b

Please sign in to comment.