TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Small program that skips over many valid nonprimes but only prints nonprimes

2 pointsby vitarnixofntrntover 1 year ago
#include &lt;stdio.h&gt;<p>unsigned integer = 0;<p>unsigned int i = 0;<p>int main (char argc, char* argv[]) {<p><pre><code> while (i&lt;1000) { integer = integer + i; i = i + 1; printf(&quot;%u\n&quot;, integer); }</code></pre> };<p>Feel free to tell me ways to improve this.

1 comment

schoenover 1 year ago
The numbers generated by your program are called the triangular numbers:<p><a href="https:&#x2F;&#x2F;oeis.org&#x2F;A000217" rel="nofollow">https:&#x2F;&#x2F;oeis.org&#x2F;A000217</a><p>This is because of the relationship between the triangular numbers and the summation formula for integers.<p>Quite a lot is known about these and you can read references to a lot of it on that OEIS page (although some of it is kind of terse and assumes certain kinds of mathematical background). One thing you&#x27;ll see there is a simple formula for computing these directly rather than by these repeated additions.<p>The primality issue is discussed at, for example,<p><a href="https:&#x2F;&#x2F;math.stackexchange.com&#x2F;questions&#x2F;1012320&#x2F;how-many-prime-numbers-are-also-triangular-numbers" rel="nofollow">https:&#x2F;&#x2F;math.stackexchange.com&#x2F;questions&#x2F;1012320&#x2F;how-many-pr...</a><p>If you ever write a program that generates a particular sequence and you want to know whether that sequence has already been studied in mathematics, OEIS has a <i>great</i> search engine tool which lets you search for specific integer sequences just by entering their terms. The results will show you huge amounts of detail about what mathematicians have already discussed and discovered about that sequence, possibly including other ways of generating it, or other sequences or formulas that are related to it somehow.<p>Edit: I feel it would be more idiomatic in C to write the main() function as something like<p><pre><code> int main(char argc, char* argv[]) { for (i = 0; i &lt; 1000; i++) { integer += i; printf(&quot;%u\n&quot;, integer); } }; </code></pre> or, if you do want to use the while loop, to at least write &quot;i++;&quot; instead of &quot;i = i + 1&quot;.<p>In modern C practice it&#x27;s also more usual to declare most variables inside of the specific function that uses them, rather than as global variables outside of any function.
评论 #39462413 未加载