Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a language-to-language conversion: from Julia to Go, same semantics. | using Primes
function propfact(n)
f = [one(n)]
for (p, x) in factor(n)
f = reduce(vcat, [f*p^i for i in 1:x], init=f)
end
pop!(f)
sort(f)
end
isabundant(n) = sum(propfact(n)) > n
prettyprintfactors(n) = (a = propfact(n); println("$n has proper divisors $a, these sum to $(sum(a))."))
function oddabundantsfrom(startingint, needed, nprint=0)
n = isodd(startingint) ? startingint : startingint + 1
count = one(n)
while count <= needed
if isabundant(n)
if nprint == 0
prettyprintfactors(n)
elseif nprint == count
prettyprintfactors(n)
end
count += 1
end
n += 2
end
end
println("First 25 abundant odd numbers:")
oddabundantsfrom(2, 25)
println("The thousandth abundant odd number:")
oddabundantsfrom(2, 1001, 1000)
println("The first abundant odd number greater than one billion:")
oddabundantsfrom(1000000000, 1)
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Port the provided Lua code into C while preserving the original functionality. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Please provide an equivalent version of this Lua code in C. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Write the same code in C# as shown below in Lua. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Convert the following code from Lua to C#, ensuring the logic remains intact. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Change the programming language of this snippet from Lua to C++ without modifying what it does. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original Lua snippet. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Generate an equivalent Java version of this Lua code. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Produce a functionally identical Java code for the snippet given in Lua. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Generate an equivalent Python version of this Lua code. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Translate this program into Python but keep the logic exactly as in Lua. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Preserve the algorithm and functionality while converting the code from Lua to VB. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Please provide an equivalent version of this Lua code in VB. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Generate a Go translation of this Lua snippet without changing its computational steps. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Convert the following code from Lua to Go, ensuring the logic remains intact. |
function sumDivs (x)
local sum, sqr = 1, math.sqrt(x)
for d = 2, sqr do
if x % d == 0 then
sum = sum + d
if d ~= sqr then sum = sum + (x/d) end
end
end
return sum
end
function oddAbundants (mode, limit)
local n, count, divlist, divsum = 1, 0, {}
repeat
n = n + 2
divsum = sumDivs(n)
if divsum > n then
table.insert(divlist, {n, divsum})
count = count + 1
if mode == "Above" and n > limit then return divlist[#divlist] end
end
until count == limit
if mode == "First" then return divlist end
if mode == "Nth" then return divlist[#divlist] end
end
function showResult (msg, t)
print(msg .. ": the proper divisors of " .. t[1] .. " sum to " .. t[2])
end
for k, v in pairs(oddAbundants("First", 25)) do showResult(k, v) end
showResult("1000", oddAbundants("Nth", 1000))
showResult("Above 1e6", oddAbundants("Above", 1e6))
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Translate the given Mathematica code snippet into C without altering its behavior. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Change the programming language of this snippet from Mathematica to C without modifying what it does. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Mathematica to C#. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Write the same algorithm in C# as shown in this Mathematica implementation. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Write the same code in C++ as shown below in Mathematica. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Convert this Mathematica block to C++, preserving its control flow and logic. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Port the provided Mathematica code into Java while preserving the original functionality. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Write a version of this Mathematica function in Java with identical behavior. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Produce a language-to-language conversion: from Mathematica to Python, same semantics. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Convert this Mathematica snippet to Python and keep its semantics consistent. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Write a version of this Mathematica function in VB with identical behavior. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Convert this Mathematica snippet to VB and keep its semantics consistent. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Produce a language-to-language conversion: from Mathematica to Go, same semantics. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Ensure the translated Go code behaves exactly like the original Mathematica snippet. | ClearAll[AbundantQ]
AbundantQ[n_] := TrueQ[Greater[Total @ Most @ Divisors @ n, n]]
res = {};
i = 1;
While[Length[res] < 25,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
res = {};
i = 1;
While[Length[res] < 1000,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res[[-1]]
res = {};
i = 1000000001;
While[Length[res] < 1,
If[AbundantQ[i],
AppendTo[res, {i, Total @ Most @ Divisors @ i}];
];
i += 2;
];
res
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Port the provided Nim code into C while preserving the original functionality. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Write the same algorithm in C as shown in this Nim implementation. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Translate the given Nim code snippet into C# without altering its behavior. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Change the following Nim code into C# without altering its purpose. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Preserve the algorithm and functionality while converting the code from Nim to C++. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Write the same code in C++ as shown below in Nim. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Translate the given Nim code snippet into Java without altering its behavior. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Translate the given Nim code snippet into Java without altering its behavior. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Can you help me rewrite this code in Python instead of Nim, keeping it the same logically? | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Write a version of this Nim function in Python with identical behavior. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Rewrite this program in VB while keeping its functionality equivalent to the Nim version. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Translate this program into Go but keep the logic exactly as in Nim. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Convert the following code from Nim to Go, ensuring the logic remains intact. | from math import sqrt
import strformat
proc sumProperDivisors(n: int): int =
result = 1
for d in countup(3, sqrt(n.toFloat).int, 2):
if n mod d == 0:
inc result, d
if n div d != d:
inc result, n div d
iterator oddAbundant(start: int): tuple[n, s: int] =
var n = start + (start and 1 xor 1)
while true:
let s = n.sumProperDivisors()
if s > n:
yield (n, s)
inc n, 2
echo "List of 25 first odd abundant numbers."
echo "Rank Number Proper divisors sum"
echo "---- ----- -------------------"
var rank = 0
for (n, s) in oddAbundant(1):
inc rank
echo fmt"{rank:2}: {n:5} {s:5}"
if rank == 25:
break
echo ""
rank = 0
for (n, s) in oddAbundant(1):
inc rank
if rank == 1000:
echo fmt"The 1000th odd abundant number is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
echo ""
for (n, s) in oddAbundant(1_000_000_000):
if n > 1_000_000_000:
echo fmt"The first odd abundant number greater than 1000000000 is {n}."
echo fmt"The sum of its proper divisors is {s}."
break
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Convert the following code from Pascal to C, ensuring the logic remains intact. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Port the provided Pascal code into C while preserving the original functionality. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Pascal snippet. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Convert the following code from Pascal to C#, ensuring the logic remains intact. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Convert this Pascal snippet to C++ and keep its semantics consistent. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Change the following Pascal code into C++ without altering its purpose. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Convert the following code from Pascal to Java, ensuring the logic remains intact. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Please provide an equivalent version of this Pascal code in Java. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Please provide an equivalent version of this Pascal code in Python. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Ensure the translated Python code behaves exactly like the original Pascal snippet. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Produce a functionally identical VB code for the snippet given in Pascal. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Convert this Pascal block to VB, preserving its control flow and logic. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Change the following Pascal code into Go without altering its purpose. | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Can you help me rewrite this code in Go instead of Pascal, keeping it the same logically? | program AbundantOddNumbers;
uses
SysUtils;
var
primes : array[0..6541] of Word;
procedure InitPrimes;
var
p : array[word] of byte;
i,j : NativeInt;
Begin
fillchar(p,SizeOf(p),#0);
p[0] := 1;
p[1] := 1;
For i := 2 to high(p) do
if p[i] = 0 then
begin
j := i*i;
IF j>high(p) then
BREAK;
while j <= High(p) do
begin
p[j] := 1;
inc(j,i);
end;
end;
j := 0;
For i := 2 to high(p) do
IF p[i] = 0 then
Begin
primes[j] := i;
inc(j);
end;
end;
function PotToString(N: NativeUint):String;
var
pN,pr,PowerPr,rest : NativeUint;
begin
pN := 0;
Result := '';
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
result := result+IntToStr(pr);
N := rest;
rest := N div pr;
PowerPr := 1;
while rest*pr = N do
begin
inc(PowerPr);
N := rest;
rest := N div pr;
end;
if PowerPr > 1 then
result := result+'^'+IntToStr(PowerPr);
if N > 1 then
result := result +'*';
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result+IntToStr(N);
end;
function OutNum(N: NativeUint):string;
Begin
result := Format('%10u= %s', [N,PotToString(N)]);
end;
function SumProperDivisors(N: NativeUint): NativeUint;
var
pN,pr,PowerPr,SumOfPower,rest,N0 : NativeUint;
begin
N0 := N;
pN := 0;
Result := 1;
repeat
pr := primes[pN];
rest := N div pr;
if rest < pr then
BREAK;
if rest*pr = N then
begin
PowerPr := 1;
SumOfPower:= 1;
repeat
PowerPr := PowerPr*pr;
inc(SumOfPower,PowerPr);
N := rest;
rest := N div pr;
until N <> rest*pr;
result := result*SumOfPower;
end;
inc(pN);
until pN > High(Primes);
if N <> 1 then
result := result*(N+1);
result := result-N0;
end;
var
C, N,N0,k: Cardinal;
begin
InitPrimes;
k := High(k);
N := 1;
N0 := N;
C := 0;
while C < 25 do begin
inc(N, 2);
if N < SumProperDivisors(N) then begin
Inc(C);
WriteLn(Format('%5u: %s', [C,OutNum(N)]));
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
Writeln(' Min Delta ',k);
writeln;
while C < 1000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn(' 1000: ',OutNum(N));
Writeln(' Min Delta ',k);
writeln;
while C < 10000 do begin
Inc(N, 2);
if N < SumProperDivisors(N) then
Begin
Inc(C);
IF k > N-N0 then
k := N-N0;
N0 := N;
end;
end;
WriteLn('10000: ',OutNum(N));
Writeln(' Min Delta ',k);
N := 1000000001;
while N >= SumProperDivisors(N) do
Inc(N, 2);
WriteLn('The first abundant odd number above one billion is: ',OutNum(N));
end.
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Produce a language-to-language conversion: from Perl to C, same semantics. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Convert this Perl block to C, preserving its control flow and logic. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original Perl code. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Write a version of this Perl function in C# with identical behavior. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Transform the following Perl implementation into C++, maintaining the same output and logic. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Change the following Perl code into C++ without altering its purpose. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Generate an equivalent Java version of this Perl code. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Convert the following code from Perl to Java, ensuring the logic remains intact. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Port the provided Perl code into Python while preserving the original functionality. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Write the same algorithm in Python as shown in this Perl implementation. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Write a version of this Perl function in VB with identical behavior. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Rewrite the snippet below in VB so it works the same as the original Perl code. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Can you help me rewrite this code in Go instead of Perl, keeping it the same logically? | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Convert this Perl block to Go, preserving its control flow and logic. | use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum: %s = %d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Write the same algorithm in C as shown in this R implementation. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Write the same algorithm in C as shown in this R implementation. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Can you help me rewrite this code in C# instead of R, keeping it the same logically? |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Translate the given R code snippet into C# without altering its behavior. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Generate a C++ translation of this R snippet without changing its computational steps. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Keep all operations the same but rewrite the snippet in Java. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Port the provided R code into Java while preserving the original functionality. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Generate an equivalent Python version of this R code. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Write the same code in Python as shown below in R. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Translate this program into VB but keep the logic exactly as in R. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from R to VB. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Convert this R block to Go, preserving its control flow and logic. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Write the same algorithm in Go as shown in this R implementation. |
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x %% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Change the programming language of this snippet from Racket to C without modifying what it does. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Translate this program into C but keep the logic exactly as in Racket. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Convert this Racket snippet to C# and keep its semantics consistent. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Port the following code from Racket to C# with equivalent syntax and logic. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
public static class AbundantOddNumbers
{
public static void Main() {
WriteLine("First 25 abundant odd numbers:");
foreach (var x in AbundantNumbers().Take(25)) WriteLine(x.Format());
WriteLine();
WriteLine($"The 1000th abundant odd number: {AbundantNumbers().ElementAt(999).Format()}");
WriteLine();
WriteLine($"First abundant odd number > 1b: {AbundantNumbers(1_000_000_001).First().Format()}");
}
static IEnumerable<(int n, int sum)> AbundantNumbers(int start = 3) =>
start.UpBy(2).Select(n => (n, sum: n.DivisorSum())).Where(x => x.sum > x.n);
static int DivisorSum(this int n) => 3.UpBy(2).TakeWhile(i => i * i <= n).Where(i => n % i == 0)
.Select(i => (a:i, b:n/i)).Sum(p => p.a == p.b ? p.a : p.a + p.b) + 1;
static IEnumerable<int> UpBy(this int n, int step) {
for (int i = n; ; i+=step) yield return i;
}
static string Format(this (int n, int sum) pair) => $"{pair.n:N0} with sum {pair.sum:N0}";
}
|
Convert the following code from Racket to C++, ensuring the logic remains intact. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Generate a C++ translation of this Racket snippet without changing its computational steps. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs{ 1 };
std::vector<int> divs2;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) {
int j = n / i;
divs.push_back(i);
if (i != j) {
divs2.push_back(j);
}
}
}
std::copy(divs2.crbegin(), divs2.crend(), std::back_inserter(divs));
return divs;
}
int sum(const std::vector<int>& divs) {
return std::accumulate(divs.cbegin(), divs.cend(), 0);
}
std::string sumStr(const std::vector<int>& divs) {
auto it = divs.cbegin();
auto end = divs.cend();
std::stringstream ss;
if (it != end) {
ss << *it;
it = std::next(it);
}
while (it != end) {
ss << " + " << *it;
it = std::next(it);
}
return ss.str();
}
int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) {
int count = countFrom;
int n = searchFrom;
for (; count < countTo; n += 2) {
auto divs = divisors(n);
int tot = sum(divs);
if (tot > n) {
count++;
if (printOne && count < countTo) {
continue;
}
auto s = sumStr(divs);
if (printOne) {
printf("%d < %s = %d\n", n, s.c_str(), tot);
} else {
printf("%2d. %5d < %s = %d\n", count, n, s.c_str(), tot);
}
}
}
return n;
}
int main() {
using namespace std;
const int max = 25;
cout << "The first " << max << " abundant odd numbers are:\n";
int n = abundantOdd(1, 0, 25, false);
cout << "\nThe one thousandth abundant odd number is:\n";
abundantOdd(n, 25, 1000, true);
cout << "\nThe first abundant odd number above one billion is:\n";
abundantOdd(1e9 + 1, 0, 1, true);
return 0;
}
|
Transform the following Racket implementation into Java, maintaining the same output and logic. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Produce a language-to-language conversion: from Racket to Java, same semantics. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Racket version. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Port the following code from Racket to Python with equivalent syntax and logic. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
|
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n % d == 0:
sum += d
otherD = n // d
if otherD != d:
sum += otherD
return sum
print ("The first 25 abundant odd numbers:")
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
aCount += 1
oddNumber += 2
print ("\n1000th abundant odd number:")
print (" ",(oddNumber - 2)," proper divisor sum: ",dSum)
oddNumber = 1000000001
found = False
while not found :
dSum = divisorSum(oddNumber )
if dSum > oddNumber :
found = True
print ("\nFirst abundant odd number > 1 000 000 000:")
print (" ",oddNumber," proper divisor sum: ",dSum)
oddNumber += 2
|
Write the same code in VB as shown below in Racket. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Generate an equivalent VB version of this Racket code. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| Module AbundantOddNumbers
Private Function divisorSum(n As Integer) As Integer
Dim sum As Integer = 1
For d As Integer = 2 To Math.Round(Math.Sqrt(n))
If n Mod d = 0 Then
sum += d
Dim otherD As Integer = n \ d
IF otherD <> d Then
sum += otherD
End If
End If
Next d
Return sum
End Function
Public Sub Main(args() As String)
Dim oddNumber As Integer = 1
Dim aCount As Integer = 0
Dim dSum As Integer = 0
Console.Out.WriteLine("The first 25 abundant odd numbers:")
Do While aCount < 25
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
Console.Out.WriteLine(oddNumber.ToString.PadLeft(6) & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
Do While aCount < 1000
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
aCount += 1
End If
oddNumber += 2
Loop
Console.Out.WriteLine("1000th abundant odd number:")
Console.Out.WriteLine(" " & (oddNumber - 2) & " proper divisor sum: " & dSum)
oddNumber = 1000000001
Dim found As Boolean = False
Do While Not found
dSum = divisorSum(oddNumber)
If dSum > oddNumber Then
found = True
Console.Out.WriteLine("First abundant odd number > 1 000 000 000:")
Console.Out.WriteLine(" " & oddNumber & " proper divisor sum: " & dSum)
End If
oddNumber += 2
Loop
End Sub
End Module
|
Produce a functionally identical Go code for the snippet given in Racket. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Write a version of this Racket function in Go with identical behavior. | #lang racket
(require math/number-theory
racket/generator)
(define (make-generator start)
(in-generator
(for ([n (in-naturals start)] #:when (odd? n))
(define divisor-sum (- (apply + (divisors n)) n))
(when (> divisor-sum n) (yield (list n divisor-sum))))))
(for/list ([i (in-range 25)] [x (make-generator 0)]) x)
(for/last ([i (in-range 1000)] [x (make-generator 0)]) x)
(for/first ([x (make-generator (add1 (inexact->exact 1e9)))]) x)
| package main
import (
"fmt"
"strconv"
)
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs2) - 1; i >= 0; i-- {
divs = append(divs, divs2[i])
}
return divs
}
func sum(divs []int) int {
tot := 0
for _, div := range divs {
tot += div
}
return tot
}
func sumStr(divs []int) string {
s := ""
for _, div := range divs {
s += strconv.Itoa(div) + " + "
}
return s[0 : len(s)-3]
}
func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int {
count := countFrom
n := searchFrom
for ; count < countTo; n += 2 {
divs := divisors(n)
if tot := sum(divs); tot > n {
count++
if printOne && count < countTo {
continue
}
s := sumStr(divs)
if !printOne {
fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot)
} else {
fmt.Printf("%d < %s = %d\n", n, s, tot)
}
}
}
return n
}
func main() {
const max = 25
fmt.Println("The first", max, "abundant odd numbers are:")
n := abundantOdd(1, 0, 25, false)
fmt.Println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
fmt.Println("\nThe first abundant odd number above one billion is:")
abundantOdd(1e9+1, 0, 1, true)
}
|
Keep all operations the same but rewrite the snippet in C. |
parse arg Nlow Nuno Novr .
if Nlow=='' | Nlow=="," then Nlow= 25
if Nuno=='' | Nuno=="," then Nuno= 1000
if Novr=='' | Novr=="," then Novr= 1000000000
numeric digits max(9, length(Novr) )
@= 'odd abundant number'
#= 0
do j=3 by 2 until #>=Nlow; $= sigO(j)
if $<=j then iterate
#= # + 1
say rt(th(#)) @ 'is:'rt(commas(j), 8) rt("sigma=") rt(commas($), 9)
end
say
#= 0
do j=3 by 2; $= sigO(j)
if $<=j then iterate
#= # + 1
if #<Nuno then iterate
say rt(th(#)) @ 'is:'rt(commas(j), 8) rt("sigma=") rt(commas($), 9)
leave
end
say
do j=1+Novr%2*2 by 2; $= sigO(j)
if $<=j then iterate
say rt(th(1)) @ 'over' commas(Novr) "is: " commas(j) rt('sigma=') commas($)
leave
end
exit
commas:parse arg _; do c_=length(_)-3 to 1 by -3; _=insert(',', _, c_); end; return _
rt: procedure; parse arg #,len; if len=='' then len= 20; return right(#, len)
th: parse arg th; return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
sigO: parse arg x; s= 1
do k=3 by 2 while k*k<x
if x//k==0 then s= s + k + x%k
end
if k*k==x then return s + k
return s
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Transform the following REXX implementation into C, maintaining the same output and logic. |
parse arg Nlow Nuno Novr .
if Nlow=='' | Nlow=="," then Nlow= 25
if Nuno=='' | Nuno=="," then Nuno= 1000
if Novr=='' | Novr=="," then Novr= 1000000000
numeric digits max(9, length(Novr) )
@= 'odd abundant number'
#= 0
do j=3 by 2 until #>=Nlow; $= sigO(j)
if $<=j then iterate
#= # + 1
say rt(th(#)) @ 'is:'rt(commas(j), 8) rt("sigma=") rt(commas($), 9)
end
say
#= 0
do j=3 by 2; $= sigO(j)
if $<=j then iterate
#= # + 1
if #<Nuno then iterate
say rt(th(#)) @ 'is:'rt(commas(j), 8) rt("sigma=") rt(commas($), 9)
leave
end
say
do j=1+Novr%2*2 by 2; $= sigO(j)
if $<=j then iterate
say rt(th(1)) @ 'over' commas(Novr) "is: " commas(j) rt('sigma=') commas($)
leave
end
exit
commas:parse arg _; do c_=length(_)-3 to 1 by -3; _=insert(',', _, c_); end; return _
rt: procedure; parse arg #,len; if len=='' then len= 20; return right(#, len)
th: parse arg th; return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
sigO: parse arg x; s= 1
do k=3 by 2 while k*k<x
if x//k==0 then s= s + k + x%k
end
if k*k==x then return s + k
return s
| #include <stdio.h>
#include <math.h>
unsigned sum_proper_divisors(const unsigned n) {
unsigned sum = 1;
for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
int main(int argc, char const *argv[]) {
unsigned n, c;
for (n = 1, c = 0; c < 25; n += 2) if (n < sum_proper_divisors(n)) printf("%u: %u\n", ++c, n);
for ( ; c < 1000; n += 2) if (n < sum_proper_divisors(n)) c ++;
printf("\nThe one thousandth abundant odd number is: %u\n", n);
for (n = 1000000001 ;; n += 2) if (n < sum_proper_divisors(n)) break;
printf("The first abundant odd number above one billion is: %u\n", n);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.