برنامه محاسبه مجموع اعداد از ۱ تا n — راهنمای کاربردی

آخرین به‌روزرسانی: ۲۵ تیر ۱۳۹۸
زمان مطالعه: ۱۵ دقیقه
برنامه محاسبه مجموع اعداد از ۱ تا n -- به زبان ساده

در این مطلب، آموزش نوشتن برنامه محاسبه مجموع اعداد از ۱ تا n به همراه کد پیاده‌سازی روش‌های مذکور در زبان‌های برنامه‌نویسی گوناگون شامل ++C، «جاوا» (Java)، «پایتون» (Python)، «سی‌شارپ» (#C) و «پی‌اچ‌پی» (PHP) ارائه شده است. فرض می‌شود که عدد n داده شده است. هدف، پیدا کردن مجموع همه اعداد از ۱ تا n است.

مثال:

Input: n = 5
Output: Sum of digits in numbers from 1 to 5 = 15

Input: n = 12
Output: Sum of digits in numbers from 1 to 12 = 51

Input: n = 328
Output: Sum of digits in numbers from 1 to 328 = 3241

روش اول برای محاسبه مجموع اعداد از ۱ تا n

یک راهکار ساده و پیش پا افتاده برای حل مساله بیان شده، شروع از ۱ تا n و محاسبه مجموع در x، با پیمایش همه ارقام x است. در زیر، روش پیاده‌سازی این مورد بیان شده است.

برنامه محاسبه مجموع اعداد از ۱ تا n در ++C

// A Simple C++ program to compute sum of digits in numbers from 1 to n 
#include<bits/stdc++.h> 
using namespace std; 
  
int sumOfDigits(int ); 
  
// Returns sum of all digits in numbers from 1 to n 
int sumOfDigitsFrom1ToN(int n) 
{ 
    int result = 0; // initialize result 
  
    // One by one compute sum of digits in every number from 
    // 1 to n 
    for (int x = 1; x <= n; x++) 
        result += sumOfDigits(x); 
  
    return result; 
} 
  
// A utility function to compute sum of digits in a 
// given number x 
int sumOfDigits(int x) 
{ 
    int sum = 0; 
    while (x != 0) 
    { 
        sum += x %10; 
        x   = x /10; 
    } 
    return sum; 
} 
  
// Driver Program 
int main() 
{ 
    int n = 328; 
    cout << "Sum of digits in numbers from 1 to " << n << " is "
         << sumOfDigitsFrom1ToN(n); 
    return 0; 
}

برنامه محاسبه مجموع اعداد از ۱ تا n در جاوا

// A Simple JAVA program to compute sum of 
// digits in numbers from 1 to n 
import java.io.*; 
  
class GFG { 
      
    // Returns sum of all digits in numbers  
    // from 1 to n 
    static int sumOfDigitsFrom1ToN(int n) 
    { 
        int result = 0; // initialize result 
       
        // One by one compute sum of digits 
        // in every number from 1 to n 
        for (int x = 1; x <= n; x++) 
            result += sumOfDigits(x); 
       
        return result; 
    } 
       
    // A utility function to compute sum  
    // of digits in a given number x 
    static int sumOfDigits(int x) 
    { 
        int sum = 0; 
        while (x != 0) 
        { 
            sum += x % 10; 
            x   = x / 10; 
        } 
        return sum; 
    } 
       
    // Driver Program 
    public static void main(String args[]) 
    { 
        int n = 328; 
        System.out.println("Sum of digits in numbers"
                          +" from 1 to " + n + " is "
                          + sumOfDigitsFrom1ToN(n)); 
    } 
} 
  
/*This code is contributed by Nikita Tiwari.*/

برنامه محاسبه مجموع اعداد از ۱ تا n در پایتون ۳

# A Simple Python program to compute sum 
# of digits in numbers from 1 to n 
  
# Returns sum of all digits in numbers  
# from 1 to n 
def sumOfDigitsFrom1ToN(n) : 
  
    result = 0   # initialize result 
   
    # One by one compute sum of digits  
    # in every number from 1 to n 
    for x in range(1, n+1) : 
        result = result + sumOfDigits(x) 
   
    return result 
  
# A utility function to compute sum of  
# digits in a given number x 
def sumOfDigits(x) : 
    sum = 0
    while (x != 0) : 
        sum = sum + x % 10
        x   = x // 10
      
    return sum
  
  
# Driver Program 
n = 328
print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n)) 
  
  
# This code is contributed by Nikita Tiwari. 

برنامه محاسبه مجموع اعداد از ۱ تا n در #C

// A Simple C# program to compute sum of 
// digits in numbers from 1 to n 
  
using System; 
  
public class GFG { 
      
    // Returns sum of all digits in numbers  
    // from 1 to n 
    static int sumOfDigitsFrom1ToN(int n) 
    { 
          
        // initialize result 
        int result = 0; 
      
        // One by one compute sum of digits 
        // in every number from 1 to n 
        for (int x = 1; x <= n; x++) 
            result += sumOfDigits(x); 
      
        return result; 
    } 
      
    // A utility function to compute sum  
    // of digits in a given number x 
    static int sumOfDigits(int x) 
    { 
        int sum = 0; 
          
        while (x != 0) 
        { 
            sum += x % 10; 
            x = x / 10; 
        } 
          
        return sum; 
    } 
      
    // Driver Program 
    public static void Main() 
    { 
        int n = 328; 
          
        Console.WriteLine("Sum of digits"
               + " in numbers from 1 to "
                             + n + " is "
                + sumOfDigitsFrom1ToN(n)); 
    } 
} 
  
// This code is contributed by shiv_bhakt.

برنامه محاسبه مجموع اعداد از ۱ تا n در PHP

<?php 
  
// A Simple php program to compute sum  
//of digits in numbers from 1 to n 
  
// Returns sum of all digits in 
// numbers from 1 to n 
function sumOfDigitsFrom1ToN($n) 
{ 
    $result = 0; // initialize result 
  
    // One by one compute sum of digits 
    // in every number from 1 to n 
    for ($x = 1; $x <= $n; $x++) 
        $result += sumOfDigits($x); 
  
    return $result; 
} 
  
// A utility function to compute sum 
// of digits in a given number x 
function sumOfDigits($x) 
{ 
    $sum = 0; 
    while ($x != 0) 
    { 
        $sum += $x %10; 
        $x = $x /10; 
    } 
    return $sum; 
} 
  
// Driver Program 
  
    $n = 328; 
    echo "Sum of digits in numbers from" 
               . " 1 to " . $n . " is " 
               . sumOfDigitsFrom1ToN($n); 
      
// This code is contributed by ajit 
?>

خروجی

خروجی قطعه کدهای بالا برای n = ۳۲۸ به صورت زیر است.

Sum of digits in numbers from 1 to 328 is 3241

روش دوم محاسبه مجموع اعداد از ۱ تا n

راهکار بالا، روش ساده‌ای است. در ادامه، یک روش موثرتر برای حل مساله مذکور ارائه می‌شود. مثال‌های زیر در این راستا قابل توجه هستند.

sum(9) = 1 + 2 + 3 + 4 ........... + 9
       = 9*10/2 
       = 45

sum(99)  = 45 + (10 + 45) + (20 + 45) + ..... (90 + 45)
         = 45*10 + (10 + 20 + 30 ... 90)
         = 45*10 + 10(1 + 2 + ... 9)
         = 45*10 + 45*10
         = sum(9)*10 + 45*10 

sum(999) = sum(99)*10 + 45*100

به طور کلی، می‌توان (sum(10d – 1 را با استفاده از رابطه زیر محاسبه کرد.

 sum(10d - 1) = sum(10d-1 - 1) * 10 + 45*(10d-1)

در کدهای ارائه شده در پایین، فرمول بالا با استفاده از «برنامه‌نویسی پویا» (Dynamic Programming) استفاده شده است، زیرا چند زیرمساله دارای هم‌پوشانی وجود دارد. فرمول بالا گام اصلی روش مورد استفاده است. در ادامه، الگوریتم کامل آمده است.

الگوریتم محاسبه مجموع اعداد از ۱ تا n

  1. تعداد ارقام از ۱ تا n، منهای یکی را پیدا کن. این مقدار را d بنام. (برای ۳۲۸، مقدار d برابر با ۲ است.)
  2. مجموع ارقام از ۱ تا 10d – 1 را محاسبه کن. این مجموع را w بنام. برای ۳۲۸، مجموع اعداد از ۱ تا ۹۹ را با استفاده از فرمول بالا محاسبه کن. (برای ۳۲۸، مجموع ارقام از ۱ تا ۹۹ با استفاده از فرمول بالا محاسبه می‌شود.)
  3. موثرترین رقم (Most significant digit | msd) در n را پیدا کن. (برای ۳۲۸، msd عدد ۳ است.)
  4. مجموع کل، برابر با مجموع عبارات زیر است.
    • مجموع ارقام از ۱ تا «msd * 10d – 1». برای ۳۲۸، مجموع ارقام از ۱ تا ۲۹۹ است. (برای ۳۲۸، مقدار 3*sum(99) + (1 + 2)*100 محاسبه می‌شود. توجه به این نکته لازم است که (sum(299 برابر با (sum(99 به علاوه ارقام از ۱۰۰ تا ۱۹۹ به علاوه ارقام از ۲۰۰ تا ۲۹۹ است. مجموع ۱۰۰ تا ۱۹۹، برابر است با sum(99) + 1*100 و مجموع ۲۹۹ برابر است با sum(99) + 2*100. به طور کلی، این مجموع را می‌توان به صورت w*msd + (msd*(msd-1)/2)*10d محاسبه کرد.
    • مجموع ارقام از msd * 10d تا n را محاسبه کن. (برای ۳۲۸، مجموع ارقام از ۳۰۰ تا ۳۲۸ باید محاسبه شود. برای ۳۲۸، این مجموع به صورت 3*29 + فراخوانی بازگشتی (sum(28 محاسبه می‌شود. به طور کلی، این مجموع را می‌توان به صورت ((msd * (n % (msd*10d) + 1) + sum(n % (10d محاسبه کرد.)
  5. در ادامه، پیاده‌سازی الگوریتم بالا ارائه شده است.

برنامه محاسبه مجموع اعداد از ۱ تا n در ++C

// C++ program to compute sum of digits in numbers from 1 to n 
#include<bits/stdc++.h> 
using namespace std; 
  
// Function to computer sum of digits in numbers from 1 to n 
// Comments use example of 328 to explain the code 
int sumOfDigitsFrom1ToN(int n) 
{ 
    // base case: if n<10 return sum of 
    // first n natural numbers 
    if (n<10) 
      return n*(n+1)/2; 
  
    // d = number of digits minus one in n. For 328, d is 2 
    int d = log10(n); 
  
    // computing sum of digits from 1 to 10^d-1, 
    // d=1 a[0]=0; 
    // d=2 a[1]=sum of digit from 1 to 9 = 45 
    // d=3 a[2]=sum of digit from 1 to 99 = a[1]*10 + 45*10^1 = 900 
    // d=4 a[3]=sum of digit from 1 to 999 = a[2]*10 + 45*10^2 = 13500 
    int *a = new int[d+1]; 
    a[0] = 0, a[1] = 45; 
    for (int i=2; i<=d; i++) 
        a[i] = a[i-1]*10 + 45*ceil(pow(10,i-1)); 
  
    // computing 10^d 
    int p = ceil(pow(10, d)); 
  
    // Most significant digit (msd) of n, 
    // For 328, msd is 3 which can be obtained using 328/100 
    int msd = n/p; 
  
    // EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE 
    // First two terms compute sum of digits from 1 to 299 
    // (sum of digits in range 1-99 stored in a[d]) + 
    // (sum of digits in range 100-199, can be calculated as 1*100 + a[d] 
    // (sum of digits in range 200-299, can be calculated as 2*100 + a[d] 
    //  The above sum can be written as 3*a[d] + (1+2)*100 
  
    // EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE 
    // The last two terms compute sum of digits in number from 300 to 328 
    // The third term adds 3*29 to sum as digit 3 occurs in all numbers  
    //                from 300 to 328 
    // The fourth term recursively calls for 28 
    return msd*a[d] + (msd*(msd-1)/2)*p +   
           msd*(1+n%p) + sumOfDigitsFrom1ToN(n%p); 
} 
  
// Driver Program 
int main() 
{ 
    int n = 328; 
    cout << "Sum of digits in numbers from 1 to " << n << " is "
         << sumOfDigitsFrom1ToN(n); 
    return 0; 
}

برنامه محاسبه مجموع اعداد از ۱ تا n در جاوا

// JAVA program to compute sum of digits  
// in numbers from 1 to n 
import java.io.*; 
import java.math.*; 
  
class GFG{ 
      
    // Function to computer sum of digits in  
    // numbers from 1 to n. Comments use  
    // example of 328 to explain the code 
    static int sumOfDigitsFrom1ToN(int n) 
    { 
        // base case: if n<10 return sum of 
        // first n natural numbers 
        if (n < 10) 
          return (n * (n + 1) / 2); 
       
        // d = number of digits minus one in 
        // n. For 328, d is 2 
        int d = (int)(Math.log10(n)); 
       
        // computing sum of digits from 1 to 10^d-1, 
        // d=1 a[0]=0; 
        // d=2 a[1]=sum of digit from 1 to 9 = 45 
        // d=3 a[2]=sum of digit from 1 to 99 =  
        // a[1]*10 + 45*10^1 = 900 
        // d=4 a[3]=sum of digit from 1 to 999 = 
        // a[2]*10 + 45*10^2 = 13500 
        int a[] = new int[d+1]; 
        a[0] = 0; a[1] = 45; 
        for (int i = 2; i <= d; i++) 
            a[i] = a[i-1] * 10 + 45 *  
                 (int)(Math.ceil(Math.pow(10, i-1))); 
       
        // computing 10^d 
        int p = (int)(Math.ceil(Math.pow(10, d))); 
       
        // Most significant digit (msd) of n, 
        // For 328, msd is 3 which can be obtained 
        // using 328/100 
        int msd = n / p; 
       
        // EXPLANATION FOR FIRST and SECOND TERMS IN 
        // BELOW LINE OF CODE 
        // First two terms compute sum of digits from 
        // 1 to 299  
        // (sum of digits in range 1-99 stored in a[d]) + 
        // (sum of digits in range 100-199, can be  
        // calculated as 1*100 + a[d] 
        // (sum of digits in range 200-299, can be  
        // calculated as 2*100 + a[d] 
        //  The above sum can be written as 3*a[d] +  
        // (1+2)*100 
       
        // EXPLANATION FOR THIRD AND FOURTH TERMS IN  
        // BELOW LINE OF CODE 
        // The last two terms compute sum of digits in  
        // number from 300 to 328. The third term adds 
        // 3*29 to sum as digit 3 occurs in all numbers  
        // from 300 to 328. The fourth term recursively 
        // calls for 28 
        return (msd * a[d] + (msd * (msd - 1) / 2) * p +   
              msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); 
    } 
       
    // Driver Program 
    public static void main(String args[]) 
    { 
        int n = 328; 
        System.out.println("Sum of digits in numbers " + 
                          "from 1 to " +n + " is " +  
                          sumOfDigitsFrom1ToN(n)); 
    } 
} 
  
/*This code is contributed by Nikita Tiwari.*/

برنامه محاسبه مجموع اعداد از ۱ تا n در پایتون ۳

# PYTHON 3 program to compute sum of digits 
# in numbers from 1 to n 
import math 
  
# Function to computer sum of digits in  
# numbers from 1 to n. Comments use example 
# of 328 to explain the code 
def sumOfDigitsFrom1ToN( n) : 
    
    # base case: if n<10 return sum of 
    # first n natural numbers 
    if (n<10) : 
        return (n*(n+1)/2) 
   
    # d = number of digits minus one in n. 
    # For 328, d is 2 
    d = (int)(math.log10(n)) 
   
    """computing sum of digits from 1 to 10^d-1, 
    d=1 a[0]=0; 
    d=2 a[1]=sum of digit from 1 to 9 = 45 
    d=3 a[2]=sum of digit from 1 to 99 = a[1]*10  
    + 45*10^1 = 900 
    d=4 a[3]=sum of digit from 1 to 999 = a[2]*10  
    + 45*10^2 = 13500"""
    a = [0] * (d + 1) 
    a[0] = 0
    a[1] = 45
    for i in range(2, d+1) : 
        a[i] = a[i-1] * 10 + 45 * (int)(math.ceil(math.pow(10,i-1))) 
   
    # computing 10^d 
    p = (int)(math.ceil(math.pow(10, d))) 
   
    # Most significant digit (msd) of n, 
    # For 328, msd is 3 which can be obtained 
    # using 328/100 
    msd = n//p 
   
    """EXPLANATION FOR FIRST and SECOND TERMS IN 
    BELOW LINE OF CODE 
    First two terms compute sum of digits from 1 to 299 
    (sum of digits in range 1-99 stored in a[d]) + 
    (sum of digits in range 100-199, can be calculated  
    as 1*100 + a[d]. (sum of digits in range 200-299, 
    can be calculated as 2*100 + a[d] 
    The above sum can be written as 3*a[d] + (1+2)*100 
   
    EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW 
    LINE OF CODE 
    The last two terms compute sum of digits in number 
    from 300 to 328. The third term adds 3*29 to sum 
    as digit 3 occurs in all numbers from 300 to 328. 
    The fourth term recursively calls for 28"""
    return (int)(msd * a[d] + (msd*(msd-1) // 2) * p +  
           msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)) 
  
# Driver Program 
n = 328
print("Sum of digits in numbers from 1 to",  
      n ,"is",sumOfDigitsFrom1ToN(n)) 
  
  
# This code is contributed by Nikita Tiwari.

برنامه محاسبه مجموع اعداد از ۱ تا n در #C

// C# program to compute sum of digits  
// in numbers from 1 to n 
  
using System; 
  
public class GFG { 
      
    // Function to computer sum of digits in  
    // numbers from 1 to n. Comments use  
    // example of 328 to explain the code 
    static int sumOfDigitsFrom1ToN(int n) 
    { 
          
        // base case: if n<10 return sum of 
        // first n natural numbers 
        if (n < 10) 
            return (n * (n + 1) / 2); 
      
        // d = number of digits minus one in 
        // n. For 328, d is 2 
        int d = (int)(Math.Log(n) / Math.Log(10)); 
      
        // computing sum of digits from 1 to 10^d-1, 
        // d=1 a[0]=0; 
        // d=2 a[1]=sum of digit from 1 to 9 = 45 
        // d=3 a[2]=sum of digit from 1 to 99 =  
        // a[1]*10 + 45*10^1 = 900 
        // d=4 a[3]=sum of digit from 1 to 999 = 
        // a[2]*10 + 45*10^2 = 13500 
        int[] a = new int[d+1]; 
        a[0] = 0; a[1] = 45; 
          
        for (int i = 2; i <= d; i++) 
            a[i] = a[i-1] * 10 + 45 *  
                (int)(Math.Ceiling(Math.Pow(10, i-1))); 
      
        // computing 10^d 
        int p = (int)(Math.Ceiling(Math.Pow(10, d))); 
      
        // Most significant digit (msd) of n, 
        // For 328, msd is 3 which can be obtained 
        // using 328/100 
        int msd = n / p; 
      
        // EXPLANATION FOR FIRST and SECOND TERMS IN 
        // BELOW LINE OF CODE 
        // First two terms compute sum of digits from 
        // 1 to 299  
        // (sum of digits in range 1-99 stored in a[d]) + 
        // (sum of digits in range 100-199, can be  
        // calculated as 1*100 + a[d] 
        // (sum of digits in range 200-299, can be  
        // calculated as 2*100 + a[d] 
        // The above sum can be written as 3*a[d] +  
        // (1+2)*100 
      
        // EXPLANATION FOR THIRD AND FOURTH TERMS IN  
        // BELOW LINE OF CODE 
        // The last two terms compute sum of digits in  
        // number from 300 to 328. The third term adds 
        // 3*29 to sum as digit 3 occurs in all numbers  
        // from 300 to 328. The fourth term recursively 
        // calls for 28 
        return (msd * a[d] + (msd * (msd - 1) / 2) * p +  
            msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p)); 
    } 
      
    // Driver Program 
    public static void Main() 
    { 
        int n = 328; 
        Console.WriteLine("Sum of digits in numbers " + 
                             "from 1 to " +n + " is " +  
                               sumOfDigitsFrom1ToN(n)); 
    } 
} 
  
// This code is contributed by shiv_bhakt.

برنامه محاسبه مجموع اعداد از ۱ تا n در PHP

<?php 
// PHP program to compute sum of digits  
// in numbers from 1 to n 
  
// Function to computer sum of digits in  
// numbers from 1 to n. Comments use  
// example of 328 to explain the code 
function sumOfDigitsFrom1ToN($n) 
{ 
    // base case: if n<10 return sum of 
    // first n natural numbers 
    if ($n < 10) 
    return ($n * ($n + 1) / 2); 
  
    // d = number of digits minus one in 
    // n. For 328, d is 2 
    $d = (int)(log10($n)); 
  
    // computing sum of digits from 1  
    // to 10^d-1, d=1 a[0]=0; 
    // d=2 a[1]=sum of digit from 1 to 9 = 45 
    // d=3 a[2]=sum of digit from 1 to 99 =  
    // a[1]*10 + 45*10^1 = 900 
    // d=4 a[3]=sum of digit from 1 to 999 = 
    // a[2]*10 + 45*10^2 = 13500 
    $a[$d + 1] = array(); 
    $a[0] = 0; 
    $a[1] = 45; 
    for ($i = 2; $i <= $d; $i++) 
        $a[$i] = $a[$i - 1] * 10 + 45 *  
                 (int)(ceil(pow(10, $i - 1))); 
  
    // computing 10^d 
    $p = (int)(ceil(pow(10, $d))); 
  
    // Most significant digit (msd) of n, 
    // For 328, msd is 3 which can be obtained 
    // using 328/100 
    $msd = (int)($n / $p); 
  
    // EXPLANATION FOR FIRST and SECOND  
    // TERMS IN BELOW LINE OF CODE 
    // First two terms compute sum of  
    // digits from 1 to 299  
    // (sum of digits in range 1-99 stored  
    // in a[d]) + (sum of digits in range  
    // 100-199, can be calculated as 1*100 + a[d] 
    // (sum of digits in range 200-299,  
    // can be calculated as 2*100 + a[d] 
    // The above sum can be written as  
    // 3*a[d] + (1+2)*100 
  
    // EXPLANATION FOR THIRD AND FOURTH  
    // TERMS IN BELOW LINE OF CODE 
    // The last two terms compute sum of digits in  
    // number from 300 to 328. The third term adds 
    // 3*29 to sum as digit 3 occurs in all numbers  
    // from 300 to 328. The fourth term recursively 
    // calls for 28 
    return ($msd * $a[$d] + ($msd * (int)($msd - 1) / 2) * $p +  
            $msd * (1 + $n % $p) + sumOfDigitsFrom1ToN($n % $p)); 
} 
  
// Driver Code 
$n = 328; 
echo ("Sum of digits in numbers " ), 
      "from 1 to " , $n , " is ",  
       sumOfDigitsFrom1ToN($n); 
  
// This code is contributed by Sachin 
?>

خروجی

خروجی قطعه کد بالا برای n = 328 به صورت زیر است.

Sum of digits in numbers from 1 to 328 is 3241

الگوریتم کارآمد، دارای یک مزیت دیگر نیز هست. بر اساس این مزیت، تنها یک بار نیاز به محاسبه []a است، حتی وقتی که چندین ورودی وجود داشته باشد.

روش سوم محاسبه مجموع ارقام از ۱ تا n

پیاده‌سازی بالا، پیچیدگی زمانی از مرتبه (O(d2 دارد، زیرا هر فراخوانی بازگشتی، آرایه []dp را یکبار دیگر محاسبه می‌کند. اولین فراخوانی، (O(d را می‌گیرد، دومین فراخوانی (O(d-1 را می‌گیرد، سومین فراخوانی (O(d-2 را می‌گیرد و به همین صورت. نیازی به محاسبه آرایه []dp در هر فراخوانی بازگشتی نیست. در زیر، پیاده‌سازی اصلاح شده که از مرتبه (O(d است در زبان‌های #C و جاوا ارائه شده است. در اینجا، d تعداد ارقام عدد ورودی است.

برنامه بهینه محاسبه مجموع اعداد از ۱ تا n در جاوا

// JAVA program to compute sum of digits  
// in numbers from 1 to n  
import java.io.*;  
import java.math.*;  
  
class GFG{  
      
    // Function to computer sum of digits in  
    // numbers from 1 to n  
    static int sumOfDigitsFrom1ToN(int n)  
    { 
        int d = (int)(Math.log10(n)); 
        int a[] = new int[d+1];  
        a[0] = 0; a[1] = 45;  
        for (int i = 2; i <= d; i++)  
            a[i] = a[i-1] * 10 + 45 *  
                (int)(Math.ceil(Math.pow(10, i-1)));  
      
        return sumOfDigitsFrom1ToNUtil(n, a); 
    } 
     
    static int sumOfDigitsFrom1ToNUtil(int n, int a[])  
    { 
        if (n < 10)  
            return (n * (n + 1) / 2); 
        
        int d = (int)(Math.log10(n)); 
        int p = (int)(Math.ceil(Math.pow(10, d)));  
        int msd = n / p;  
        return (msd * a[d] + (msd * (msd - 1) / 2) * p +  
            msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));  
    }  
      
    // Driver Program  
    public static void main(String args[])  
    {  
        int n = 328;  
        System.out.println("Sum of digits in numbers " +  
                        "from 1 to " +n + " is " +  
                        sumOfDigitsFrom1ToN(n));  
    }  
}  
  
/*This code is contributed by Narendra Jha.*/

برنامه بهینه محاسبه مجموع اعداد از ۱ تا n در #C

// C# program to compute sum of digits  
// in numbers from 1 to n  
using System; 
  
class GFG 
{  
      
    // Function to computer sum of digits in  
    // numbers from 1 to n  
    static int sumOfDigitsFrom1ToN(int n)  
    { 
        int d = (int)(Math.Log10(n)); 
        int []a = new int[d+1];  
        a[0] = 0; a[1] = 45;  
        for (int i = 2; i <= d; i++)  
            a[i] = a[i-1] * 10 + 45 *  
                (int)(Math.Ceiling(Math.Pow(10, i-1)));  
      
        return sumOfDigitsFrom1ToNUtil(n, a); 
    } 
      
    static int sumOfDigitsFrom1ToNUtil(int n, int []a)  
    { 
        if (n < 10)  
            return (n * (n + 1) / 2); 
          
        int d = (int)(Math.Log10(n)); 
        int p = (int)(Math.Ceiling(Math.Pow(10, d)));  
        int msd = n / p;  
        return (msd * a[d] + (msd * (msd - 1) / 2) * p +  
            msd * (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a));  
    }  
      
    // Driver code  
    public static void Main(String []args)  
    {  
        int n = 328;  
        Console.WriteLine("Sum of digits in numbers " +  
                        "from 1 to " +n + " is " +  
                        sumOfDigitsFrom1ToN(n));  
    }  
}  
  
// This code contributed by Rajput-Ji

خروجی

Sum of digits in numbers from 1 to 328 is 3241

اگر نوشته بالا برای شما مفید بوده است، آموزش‌های زیر نیز به شما پیشنهاد می‌شوند:

^^

بر اساس رای ۱۰ نفر
آیا این مطلب برای شما مفید بود؟
شما قبلا رای داده‌اید!
اگر بازخوردی درباره این مطلب دارید یا پرسشی دارید که بدون پاسخ مانده است، آن را از طریق بخش نظرات مطرح کنید.
منابع:
GeeksforGeeks
۲ thoughts on “برنامه محاسبه مجموع اعداد از ۱ تا n — راهنمای کاربردی

سلام خواهشن زبان برنامه نویسی فرترن هم بزارید

سلام امکان داره دستور مجموع اعداد یک تا n در برنامه ی متلب رو هم بنویسید؟

نظر شما چیست؟

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *