Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Can you help me rewrite this code in Python instead of D, keeping it the same logically?
import std.stdio; int[] divisors(int n) { import std.range; int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= retro(divs2).array; return divs; } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { import std.algorithm.iteration; import std.array; import std.conv; 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 = divs.map!(to!string).join(" + "); if (printOne) { writefln("%d < %s = %d", n, s, tot); } else { writefln("%2d. %5d < %s = %d", count, n, s, tot); } } } return n; } void main() { const int max = 25; writefln("The first %d abundant odd numbers are:", max); int n = abundantOdd(1, 0, 25, false); writeln("\nThe one thousandth abundant odd number is:"); abundantOdd(n, 25, 1000, true); writeln("\nThe first abundant odd number above one billion is:"); abundantOdd(cast(int)(1e9 + 1), 0, 1, true); }
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 the given D code snippet into Python without altering its behavior.
import std.stdio; int[] divisors(int n) { import std.range; int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= retro(divs2).array; return divs; } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { import std.algorithm.iteration; import std.array; import std.conv; 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 = divs.map!(to!string).join(" + "); if (printOne) { writefln("%d < %s = %d", n, s, tot); } else { writefln("%2d. %5d < %s = %d", count, n, s, tot); } } } return n; } void main() { const int max = 25; writefln("The first %d abundant odd numbers are:", max); int n = abundantOdd(1, 0, 25, false); writeln("\nThe one thousandth abundant odd number is:"); abundantOdd(n, 25, 1000, true); writeln("\nThe first abundant odd number above one billion is:"); abundantOdd(cast(int)(1e9 + 1), 0, 1, true); }
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
Keep all operations the same but rewrite the snippet in VB.
import std.stdio; int[] divisors(int n) { import std.range; int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= retro(divs2).array; return divs; } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { import std.algorithm.iteration; import std.array; import std.conv; 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 = divs.map!(to!string).join(" + "); if (printOne) { writefln("%d < %s = %d", n, s, tot); } else { writefln("%2d. %5d < %s = %d", count, n, s, tot); } } } return n; } void main() { const int max = 25; writefln("The first %d abundant odd numbers are:", max); int n = abundantOdd(1, 0, 25, false); writeln("\nThe one thousandth abundant odd number is:"); abundantOdd(n, 25, 1000, true); writeln("\nThe first abundant odd number above one billion is:"); abundantOdd(cast(int)(1e9 + 1), 0, 1, true); }
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 programming language of this snippet from D to VB without modifying what it does.
import std.stdio; int[] divisors(int n) { import std.range; int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= retro(divs2).array; return divs; } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { import std.algorithm.iteration; import std.array; import std.conv; 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 = divs.map!(to!string).join(" + "); if (printOne) { writefln("%d < %s = %d", n, s, tot); } else { writefln("%2d. %5d < %s = %d", count, n, s, tot); } } } return n; } void main() { const int max = 25; writefln("The first %d abundant odd numbers are:", max); int n = abundantOdd(1, 0, 25, false); writeln("\nThe one thousandth abundant odd number is:"); abundantOdd(n, 25, 1000, true); writeln("\nThe first abundant odd number above one billion is:"); abundantOdd(cast(int)(1e9 + 1), 0, 1, true); }
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 D snippet to Go and keep its semantics consistent.
import std.stdio; int[] divisors(int n) { import std.range; int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= retro(divs2).array; return divs; } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { import std.algorithm.iteration; import std.array; import std.conv; 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 = divs.map!(to!string).join(" + "); if (printOne) { writefln("%d < %s = %d", n, s, tot); } else { writefln("%2d. %5d < %s = %d", count, n, s, tot); } } } return n; } void main() { const int max = 25; writefln("The first %d abundant odd numbers are:", max); int n = abundantOdd(1, 0, 25, false); writeln("\nThe one thousandth abundant odd number is:"); abundantOdd(n, 25, 1000, true); writeln("\nThe first abundant odd number above one billion is:"); abundantOdd(cast(int)(1e9 + 1), 0, 1, true); }
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 D to Go without modifying what it does.
import std.stdio; int[] divisors(int n) { import std.range; int[] divs = [1]; int[] divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= retro(divs2).array; return divs; } int abundantOdd(int searchFrom, int countFrom, int countTo, bool printOne) { import std.algorithm.iteration; import std.array; import std.conv; 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 = divs.map!(to!string).join(" + "); if (printOne) { writefln("%d < %s = %d", n, s, tot); } else { writefln("%2d. %5d < %s = %d", count, n, s, tot); } } } return n; } void main() { const int max = 25; writefln("The first %d abundant odd numbers are:", max); int n = abundantOdd(1, 0, 25, false); writeln("\nThe one thousandth abundant odd number is:"); abundantOdd(n, 25, 1000, true); writeln("\nThe first abundant odd number above one billion is:"); abundantOdd(cast(int)(1e9 + 1), 0, 1, true); }
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 Delphi function in C with identical behavior.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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; }
Write the same algorithm in C as shown in this Delphi implementation.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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; }
Maintain the same structure and functionality when rewriting this code in C#.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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}"; }
Write a version of this Delphi function in C# with identical behavior.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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}"; }
Transform the following Delphi implementation into C++, maintaining the same output and logic.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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; }
Write the same algorithm in C++ as shown in this Delphi implementation.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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; }
Write the same algorithm in Java as shown in this Delphi implementation.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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; } }
Can you help me rewrite this code in Java instead of Delphi, keeping it the same logically?
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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; } }
Produce a functionally identical Python code for the snippet given in Delphi.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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
Translate the given Delphi code snippet into Python without altering its behavior.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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 language-to-language conversion: from Delphi to VB, same semantics.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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
Preserve the algorithm and functionality while converting the code from Delphi to VB.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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 Delphi snippet to Go and keep its semantics consistent.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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) }
Convert this Delphi block to Go, preserving its control flow and logic.
program AbundantOddNumbers; uses SysUtils; function SumProperDivisors(const N: Cardinal): Cardinal; var I, J: Cardinal; begin Result := 1; I := 3; while I < Sqrt(N)+1 do begin if N mod I = 0 then begin J := N div I; Inc(Result, I); if I <> J then Inc(Result, J); end; Inc(I, 2); end; end; var C, N: Cardinal; begin N := 1; C := 0; while C < 25 do begin Inc(N, 2); if N < SumProperDivisors(N) then begin Inc(C); WriteLn(Format('%u: %u', [C, N])); end; end; while C < 1000 do begin Inc(N, 2); if N < SumProperDivisors(N) then Inc(C); end; WriteLn(Format('The one thousandth abundant odd number is: %u', [N])); N := 1000000001; while N >= SumProperDivisors(N) do Inc(N, 2); WriteLn(Format('The first abundant odd number above one billion is: %u', [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 C instead of F#, keeping it the same logically?
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
#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 the following code from F# to C, ensuring the logic remains intact.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
#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 following code from F# to C# with equivalent syntax and logic.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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 F# snippet without changing its computational steps.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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}"; }
Can you help me rewrite this code in C++ instead of F#, keeping it the same logically?
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
#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; }
Preserve the algorithm and functionality while converting the code from F# to C++.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
#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 Java as shown below in F#.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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 F#.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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 F# code in Python.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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
Change the following F# code into Python without altering its purpose.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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 F# function in VB with identical behavior.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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
Write the same algorithm in VB as shown in this F# implementation.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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
Port the following code from F# to Go with equivalent syntax and logic.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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 F# block to Go, preserving its control flow and logic.
let fN g=Seq.initInfinite(int64>>(+)1L)|>Seq.takeWhile(fun n->n*n<=g)|>Seq.filter(fun n->g%n=0L)|>Seq.sumBy(fun n->let i=g/n in n+(if i=n then 0L else i)) let aon n=Seq.initInfinite(int64>>(*)2L>>(+)n)|>Seq.map(fun g->(g,fN g))|>Seq.filter(fun(n,g)->2L*n<g) aon 1L|>Seq.take 25|>Seq.iter(fun(n,g)->printfn "The sum of the divisors of %d is %d" n g) let n,g=aon 1L|>Seq.item 999 in printfn "\nThe 1000th abundant odd number is %d. The sum of it's divisors is %d" n g let n,g=aon 1000000001L|>Seq.head in printfn "\nThe first abundant odd number greater than 1000000000 is %d. The sum of it's divisors is %d" n g
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 code in C as shown below in Factor.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
#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 Factor code snippet into C without altering its behavior.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
#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 Factor code into C# while preserving the original functionality.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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 Factor snippet to C# and keep its semantics consistent.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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}"; }
Ensure the translated C++ code behaves exactly like the original Factor snippet.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
#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 Factor to C++, ensuring the logic remains intact.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
#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; }
Rewrite the snippet below in Java so it works the same as the original Factor code.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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; } }
Ensure the translated Java code behaves exactly like the original Factor snippet.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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; } }
Change the following Factor code into Python without altering its purpose.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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
Transform the following Factor implementation into Python, maintaining the same output and logic.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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 Factor function in VB with identical behavior.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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 the following code from Factor to VB, ensuring the logic remains intact.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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 Factor to Go.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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) }
Generate a Go translation of this Factor snippet without changing its computational steps.
USING: arrays formatting io kernel lists lists.lazy math math.primes.factors sequences tools.memory.private ; IN: rosetta-code.abundant-odd-numbers : σ ( n -- sum ) divisors sum ; : abundant? ( n -- ? ) [ σ ] [ 2 * ] bi > ; : abundant-odds-from ( n -- list ) dup even? [ 1 + ] when [ 2 + ] lfrom-by [ abundant? ] lfilter ; : first25 ( -- seq ) 25 1 abundant-odds-from ltake list>array ; : 1,000th ( -- n ) 999 1 abundant-odds-from lnth ; : first>10^9 ( -- n ) 1,000,000,001 abundant-odds-from car ; GENERIC: show ( obj -- ) M: integer show dup σ [ commas ] bi@ "%-6s σ = %s\n" printf ; M: array show [ show ] each ; : abundant-odd-numbers-demo ( -- ) first25 "First 25 abundant odd numbers:" 1,000th "1,000th abundant odd number:" first>10^9 "First abundant odd number > one billion:" [ print show nl ] 2tri@ ; MAIN: abundant-odd-numbers-demo
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) }
Rewrite this program in C# while keeping its functionality equivalent to the Fortran version.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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 Fortran to C#.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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 Fortran.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
#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 Fortran implementation into C++, maintaining the same output and logic.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
#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 Fortran code into C without altering its purpose.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
#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 Fortran code in C.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
#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 this program in Java while keeping its functionality equivalent to the Fortran version.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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 this Fortran block to Java, preserving its control flow and logic.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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 this Fortran snippet to Python and keep its semantics consistent.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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
Change the programming language of this snippet from Fortran to Python without modifying what it does.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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 the given Fortran code snippet into VB without altering its behavior.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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
Port the provided Fortran code into VB while preserving the original functionality.
program main use,intrinsic :: iso_fortran_env, only : int8, int16, int32, int64 implicit none integer,parameter :: dp=kind(0.0d0) character(len=*),parameter :: g='(*(g0,1x))' integer :: j, icount integer,allocatable :: list(:) real(kind=dp) :: tally write(*,*)'N sum' icount=0 do j=1,huge(0)-1,2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then icount=icount+1 select case(icount) case(1:25,1000);write(*,g)icount,':',j end select endif if(icount.gt.1000)exit enddo do j=1000000001,huge(0),2 list=divisors(j) tally= sum([real(list,kind=dp)]) if(tally>2*j .and. iand(j,1) /= 0) then write(*,g)'First abundant odd number greater than one billion:',j exit endif enddo contains function divisors(num) result (numbers) integer,intent(in) :: num integer :: i integer,allocatable :: numbers(:) numbers=[integer :: ] do i=1 , int(sqrt(real(num))) if (mod(num , i) .eq. 0) numbers=[numbers, i,num/i] enddo end function divisors end program main
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 Groovy block to C, preserving its control flow and logic.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
#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 Groovy snippet.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
#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 following Groovy code into C# without altering its purpose.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Groovy to C# with equivalent syntax and logic.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 this program into C++ but keep the logic exactly as in Groovy.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
#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 Groovy code snippet into C++ without altering its behavior.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
#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; }
Rewrite the snippet below in Java so it works the same as the original Groovy code.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Java instead of Groovy, keeping it the same logically?
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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; } }
Transform the following Groovy implementation into Python, maintaining the same output and logic.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Python code for the snippet given in Groovy.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 the given Groovy code snippet into VB without altering its behavior.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Groovy code.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Groovy.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Groovy block to Go, preserving its control flow and logic.
class Abundant { static List<Integer> divisors(int n) { List<Integer> divs = new ArrayList<>() divs.add(1) List<Integer> divs2 = new ArrayList<>() int i = 2 while (i * i < n) { if (n % i == 0) { int j = (int) (n / i) divs.add(i) if (i != j) { divs2.add(j) } } i++ } Collections.reverse(divs2) divs.addAll(divs2) return divs } static int abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) { int count = countFrom int n = searchFrom while (count < countTo) { List<Integer> divs = divisors(n) int tot = divs.stream().reduce(Integer.&sum).orElse(0) if (tot > n) { count++ if (!printOne || count >= countTo) { String s = divs.stream() .map(Integer.&toString) .reduce { a, b -> a + " + " + b } .orElse("") if (printOne) { System.out.printf("%d < %s = %d\n", n, s, tot) } else { System.out.printf("%2d. %5d < %s = %d\n", count, n, s, tot) } } } n += 2 } return n } static void main(String[] args) { int max = 25 System.out.printf("The first %d abundant odd numbers are:\n", max) int n = abundantOdd(1, 0, 25, false) System.out.println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) System.out.println("\nThe first abundant odd number above one billion is:") abundantOdd((int) (1e9 + 1), 0, 1, true) } }
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 Haskell implementation.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
#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 Haskell snippet to C and keep its semantics consistent.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
#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 Haskell implementation into C#, maintaining the same output and logic.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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 this program into C# but keep the logic exactly as in Haskell.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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 Haskell to C++, ensuring the logic remains intact.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
#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; }
Produce a language-to-language conversion: from Haskell to C++, same semantics.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
#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 programming language of this snippet from Haskell to Java without modifying what it does.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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; } }
Change the following Haskell code into Python without altering its purpose.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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
Please provide an equivalent version of this Haskell code in Python.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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
Change the following Haskell code into VB without altering its purpose.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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
Maintain the same structure and functionality when rewriting this code in VB.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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
Keep all operations the same but rewrite the snippet in Go.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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 Go.
import Data.List (nub) divisorSum :: Integral a => a -> a divisorSum n = sum . map (\i -> sum $ nub [i, n `quot` i]) . filter ((== 0) . (n `rem`)) $ takeWhile ((<= n) . (^ 2)) [1 ..] oddAbundants :: Integral a => a -> [(a, a)] oddAbundants n = [ (i, divisorSum i) | i <- [n ..], odd i, divisorSum i > i * 2 ] printAbundant :: (Int, Int) -> IO () printAbundant (n, s) = putStrLn $ show n ++ " with " ++ show s ++ " as the sum of all proper divisors." main :: IO () main = do putStrLn "The first 25 odd abundant numbers are:" mapM_ printAbundant . take 25 $ oddAbundants 1 putStrLn "The 1000th odd abundant number is:" printAbundant $ oddAbundants 1 !! 1000 putStrLn "The first odd abundant number above 1000000000 is:" printAbundant . head . oddAbundants $ 10 ^ 9
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 C code behaves exactly like the original Julia snippet.
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)
#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 Julia.
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)
#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 Julia code into C# while preserving the original functionality.
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)
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}"; }
Produce a functionally identical C# code for the snippet given in Julia.
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)
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}"; }
Rewrite the snippet below in C++ so it works the same as the original Julia code.
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)
#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; }
Produce a functionally identical C++ code for the snippet given in Julia.
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)
#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; }
Rewrite this program in Java while keeping its functionality equivalent to the Julia version.
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)
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 this Julia snippet to Java and keep its semantics consistent.
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)
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 Julia code into Python while preserving the original functionality.
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)
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
Change the programming language of this snippet from Julia to Python without modifying what it does.
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)
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 VB code behaves exactly like the original Julia snippet.
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)
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
Write the same code in VB as shown below in Julia.
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)
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
Write a version of this Julia function in Go with identical behavior.
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) }