Source

euler-totient / euler_totient.go

/*
**	Euler's Totient Solver in Go
**	Copyright (c) 2009 Aaron Toth
**
**	Just an experiment in Go, ported from a terrible
**	C program I made for a class 1 year ago.
**
**	Reference: http://en.wikipedia.org/wiki/Euler's_totient_function
 */

package main

import (
	"fmt";
	"flag";
)

func rel_prime(i, m int) int {
	var common_divisors int = 0;

	for j := 2; j <= i; j++ {
		if (i%j == 0) && (m%j == 0) {
			common_divisors++
		}
	}

	if common_divisors > 0 {
		return 0
	}
	return 1;
}

func abs_int(x int) int {
	if x <= 0 {
		return -x
	}
	return x;
}

func euler_totient(n int) int {
	var m int = abs_int(n);

	if (m == 0) || (m == 1) {
		return 1
	}

	var totient int = 0;

	for i := 1; i < m; i++ {
		if rel_prime(i, m) == 1 {
			totient++
		}
	}
	return totient;
}

func main() {
	var n *int = flag.Int("n", 0, "an integer value to calculate the number of positive integers less than or equal to n that are coprime to n");
	flag.Parse();

	fmt.Printf("The totient of %v is %v\n", *n, euler_totient(*n));
}