I'm a newbie to C++ (coming from C#) and I decided to complete this Code Golf challenge for fun (though I definitely wouldn't say it's short). Essentially, the challenge was to calculate the phi(not_pi()) of all the numbers from 1 to 100, and print them out in a loop, where
phi(n)is the number of integers less than or equal tonthat are relatively prime ton.not_pi(n)is the number of composites less than or equal ton.
Here is my code (I'm using Visual C++ 2015):
stdafx.h
#pragma once
#include "targetver.h"
#include <cmath>
#include <cstdio>
#include <tchar.h>
#include <iostream>
#include <stdexcept>
golf.cpp
#include "stdafx.h"
#define __nameof(var) #var
namespace golf
{
int gcd(int left, int right) noexcept
{
if (right == 0)
return left;
return gcd(right, left % right);
}
bool relatively_prime(int left, int right) noexcept
{
return gcd(left, right) == 1;
}
int phi(int number)
{
if (number < 0)
throw std::invalid_argument(__nameof(number));
if (number == 0)
return 0;
if (number == 1)
return 1; // 1 is the only number relatively prime to itself
int result = 1; // We're always relatively prime to 1
for (int i = 2; i < number; i++)
{
if (relatively_prime(i, number))
result++;
}
return result;
}
bool prime(int number)
{
if (number < 0)
throw std::invalid_argument(__nameof(number));
int bound = static_cast<int>(std::floor(std::sqrt(number)));
for (int i = 2; i <= bound; i++)
{
if (number % i == 0)
return false;
}
return true;
}
int not_pi(int number)
{
if (number < 0)
throw std::invalid_argument(__nameof(number));
if (number <= 3)
return 0;
int result = 1;
for (int i = 6; i <= number; i++)
{
if (!prime(i))
result++;
}
return result;
}
int main()
{
for (int i = 1; i <= 100; i++)
{
std::cout << i << " " << phi(not_pi(i)) << std::endl;
}
return 0;
}
}
int main()
{
// Glue code because I didn't realize main()
// was supposed to be in the global namespace.
return golf::main();
}
Any tips on how I could improve my C++ code? Specifically, is there anything I could do to make it more "modern"/C++11-like, or practices I should follow? Are there any sources for undefined behavior/gotchas I didn't see? I'm a beginner so any feedback/critique would be appreciated.
