Posts

Showing posts from 2018
For more Computer Science, Linux, C++ content visit ProgrammerCave
Follow us on Facebook | Instagram | Telegram

Contribute on Paypal

C++: Collatz Conjecture Program

Image
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term. Otherwise, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. [wikipedia] Image source : wolfram                            C++ implementation of Collatz conjecture #include <iostream> #include <cassert> //assert() int main() {     int n;     std::cout << "Enter number (greater than 1)\n" ;     std::cin >> n;     assert(n > 1);     std::cout << "Series is :\n" ;     std::cou...

C++: Find Prime Factors of a Number.

Image
Given a number, we have to find it's prime factors. Prime Factorization is finding which prime numbers multiply together to make the original number. [mathsisfun] You can find many such projects from here . Here is the C++ implementation to find prime factors. #include <iostream> #include <vector> std::vector< int > find_prime_factors( int n) {     std::vector< int > result;     for ( int i = 2; i <= n; i++)     {         while (n % i == 0)         {             result.push_back(i);             n = n/i;         }     }     return result; } int main() {     int n;     std::cout << "Enter number\n" ;     s...

C++: Add binary numbers

Image
We will store the binary numbers in an array. We have to store the least significant bit at index 0 and most significant bit at last index.  In   1 0 1 0  -  1 is the most significant bit and 0 is the least                         significant bit So it will be stored as  0 1 0 1 in array   C++ implementation to add binary numbers #include <iostream> #include <vector> #include <algorithm> void add(std::vector< int > & A,          std::vector< int > & B,          std::vector< int > & C) {    int size_A = A. size() ;    int size_B = B. size() ;    int max_size = (size_A >= size_B) ? size_A : size_B;    int carry = 0, sum = 0;  ...
For more Computer Science, Linux, C++ content visit ProgrammerCave
Follow us on Facebook | Instagram | Telegram

Contribute on Paypal