Skip to content

Instantly share code, notes, and snippets.

@adamcrussell
Created May 16, 2019 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrussell/dbe3cd4ec77c36f902bcce7e8e7aa5f6 to your computer and use it in GitHub Desktop.
Save adamcrussell/dbe3cd4ec77c36f902bcce7e8e7aa5f6 to your computer and use it in GitHub Desktop.
Integrating C++ and Perl with SWIG
use strict;
use warnings;
##
# Write a script that computes the first five perfect numbers.
# A perfect number is an integer that is the sum of its positive
# proper divisors (all divisors except itself).
##
use Perfect;
use constant PERFECT_COUNT => 5;
my $i = 2;
my $count = 0;
my $p = new Perfect::Perfect();
do{
if($p->isPerfect($i)){
print "$i ";
$count++;
}
$i++;
}while($count < PERFECT_COUNT);
print "\n";
use ExtUtils::MakeMaker;
WriteMakefile(
"NAME" => "Perfect", # Name of package
"OBJECT" => "perfect.o perfect_wrap.o" # Object files
);
#include "perfect.h"
Perfect::Perfect(){
}
Perfect::~Perfect(){
}
bool Perfect::isPerfect(int n){
long int sum = 1;
// Find all divisors and add them
for (long int i=2; i*i<=n; i++){
if (n%i==0){
if(i*i!=n)
sum = sum + i + n/i;
else
sum=sum+i;
}
}
if (sum == n && n != 1){
return true;
}
return false;
}
#ifndef PERFECT_H_
#define PERFECT_H_
class Perfect{
public:
Perfect();
~Perfect();
bool isPerfect(int n);
};
#endif
/* File : perfect.i */
%module Perfect
%{
#include "perfect.h"
%}
%include "perfect.h"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment